Using an anonymous struct vs a named struct with typedef

前端 未结 6 1223
小蘑菇
小蘑菇 2020-12-06 16:31

When should one of the following statements be used over the other?

typedef struct Foo {
    int a;
} Bar;

and

typedef stru         


        
6条回答
  •  有刺的猬
    2020-12-06 16:43

    When creating an opaque data type which is when the header only contains a forward declaration of the struct and the actual definition of it's members is in the source file. Since you cannot forward declare a typedef you'll have to give a struct a name. Example:

    Foo.h

    typedef struct Foo_ Foo;
    

    Foo.c

    struct Foo_ {
        int a;
    };
    

    Also when you have a recursive data structure such as linked list which everyone else has mentioned.

提交回复
热议问题