2

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.

haccks
  • 104,019
  • 25
  • 176
  • 264
James
  • 1,430
  • 4
  • 20
  • 27
  • 1
    You tagged this both `c` and `c++`. Which one of these two languages are you talking about? – sth Jul 07 '13 at 20:01
  • There's an excellent answer here: http://stackoverflow.com/questions/612328/difference-between-struct-and-typedef-struct-in-c – paj28 Jul 07 '13 at 20:02
  • It's a C API, but also works with a C++ compiler. – James Jul 07 '13 at 20:02
  • Are you talking about `struct SYSTEM` specifically or generically? Is `SYSTEM` just an example or are you trying to determine what that particular struct is for? – Vaughn Cato Jul 07 '13 at 20:10
  • Thanks, I mean that 'struct SYSTEM' has not been defined anywhere before that line of code. So it compiles, but I have no idea what a SYSTEM (or struct SYSTEM) actually is :) – James Jul 07 '13 at 20:13
  • @James: If `struct SYSTEM` is really not defined before this point (not even in a header that you include directly or indirectly,) then this line serves as a sort of a forward declaration. From this point on, `SYSTEM` will be an *incomplete type*, which means you can only declare pointers to it (and a couple of other things,) but you cannot have variables of this type until its fully defined. – yzt Jul 07 '13 at 20:35

2 Answers2

4

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.

user123
  • 8,970
  • 2
  • 31
  • 52
3

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.

ouah
  • 142,963
  • 15
  • 272
  • 331