Home > front end >  How to properly use `typedef` for structs in C?
How to properly use `typedef` for structs in C?

Time:02-26

I see a lot of different typedef usages in many C courses and examples.

Here is the CORRECT way to do this (example from ISO/IEC C language specification draft)

typedef struct tnode TNODE;

struct tnode {
    int count;
    TNODE *left, *right;
};

TNODE s, *sp;

However I see a lot of code with the following pattern:

typedef struct {
    int a;
    int b;
} ab_t;

Is this wrong for some reasons, or correct but it provides limited functionality of structs defined like this?

CodePudding user response:

What this does:

typedef struct {
    int a;
    int b;
} ab_t;

Is define an anonymous struct and give it the alias ab_t. For this case there's no problem as you can always use the alias. It would however be a problem if one of the members was a pointer to this type.

If for example you tried to do something like this:

typedef struct {
    int count;
    TNODE *left, *right;
} TNODE;

This wouldn't work because the type TNODE is not yet defined at the point it is used, and you can't use the tag of the struct (i.e. the name that comes after the struct keyword) because it doesn't have one.

CodePudding user response:

The difference between these two typedef declarations

typedef struct tnode TNODE;

struct tnode {
    int count;
    TNODE *left, *right;
};

TNODE s, *sp;

and

typedef struct {
    int a;
    int b;
} ab_t;

. is that in the second case you declared an unnamed structure. It means that within the structure you can not refer to it itself. For example you can not write fir example

typede struct {
    int count;
    TNODE *left, *right;
} TNODE;

because the name TNODE used in this member declaration

    TNODE *left, *right;

is not declared yet.

But you can refer to the structure if the structure tag will have a name like

struct tnode {
    int count;
    struct tnode *left, *right;
};

because the name struct tnode was already declared.

Another difference is that to declare a pointer to a structure there is no need to have a complete definition of the structure. That is you may write

typedef struct tnode TNODE;

TNODE *sp;

struct tnode {
    int count;
    TNODE *left, *right;
};

Pay attention to that you may write a typedef declaration also the following way

struct tnode {
    int count;
    struct tnode *left, *right;
} typedef TNODE;
  • Related