This question already has an answer here:
-
Difference between 'struct' and 'typedef struct' in C++?
8 answers
I've seen this code written at the top of an API:
typedef struct SYSTEM SYSTEM;
The type SYSTEM
was previously undefined. Does anyone know what this does? What does the compiler think a SYSTEM
after this line?
Thanks for the answers! My question is that SYSTEM was not previously defined in the file, so I have no idea what it is. For example, that line will compile by itself, but struct SYSTEM
was not defined anywhere.
It allows you in C to use the name SYSTEM
instead of using struct SYSTEM
.
The typedef
creates a synonym SYSTEM
to struct SYSTEM
.
In your case as struct SYSTEM
is not declared, the declaration also declares struct SYSTEM
as an incomplete type like in this declaration: struct SYSTEM;
.
The complete object type struct SYSTEM
can then be declared in another translation unit.
This is really only effective and useful in C.
In C, you have to type struct type
, while C++ allows you to omit the struct
part of the type and just write type
.
typedef struct type type
allows you to use type
in C without having to use the struct
keyword before the struct name.
Some C programmers regard this bad practice though, and prefer to write struct type
. Just trying to put that out there.
The reason you're not getting any errors is because that line acts as a forward declaration for the struct SYSTEM
that may or may not exist. All the typedef
does is tell the compiler that when you say X
, you mean Y
.