Search code examples
cstructdeclarationtypedefdefinition

How to properly use `typedef` for structs in C?


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?


Solution

  • 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.