Aug 20, 2020

Typedef Struct

In my digging around in C graphics programming I'm encountering examples where they sometimes define structs as typedef struct {...} A and sometimes as struct A {...}. I was a bit confused as to what the difference was. After googling it online my understanding is this:

When you typedef something, you create an alias for that type, and that protects the type name in the compiler (i.e. you are not allowed to overwrite that name to mean something different, like being a method or something like this). That is why it is more safe to do this, because this means you won't accidentally overwrite the struct type that you had previously created.

But why would you then just use struct? Well, in some cases in my examples, structs are linked lists, i.e. they have elements that are referring to themselves. For this, the compiler needs to know about the type "before it gets defined". This is why, at the top of the file a typedef struct MyType MyType is defined, and hence by the definition of the type it is not necessary to write typedef again.

Code of the Day

typedef struct MyType MyType;

struct MyType {
  char name[MAX_NAME_LENGTH];
  int typeSpec;
  MyType *next;
}