Why use different a different tag and typedef for a struct?

后端 未结 5 529
离开以前
离开以前 2020-12-09 20:11

In C code, I\'ve seen the following:

typedef struct SomeStructTag {
    // struct members
} SomeStruct;

I\'m not clear on why this is any d

5条回答
  •  清歌不尽
    2020-12-09 20:58

    There is one functional reason for using a different tag between the typedef and the struct. This is when you're doing a linked list structure, where one of the fields in your struct is a pointer to an instance of the struct being defined. Since the statement isn't complete yet, you can't use the typedef name within the statement.

    For example:

    typedef struct {
        link_t* next;
        void*   data;
    } link_t;
    

    won't work, because you're trying to use link_t before the compiler has seen the symbol. Instead, you write it so:

    typedef struct LL {
        struct LL* next;
        void*      data;
    } link_t;
    

    and struct LL is known to the compiler one line before you use it.

提交回复
热议问题