Using an anonymous struct vs a named struct with typedef

前端 未结 6 1236
小蘑菇
小蘑菇 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:48

    The term anonymous struct is already used for something else: in nested structs (or unions) that don't have a name at all and whose fields are referred to as if they were entries in the parent.

    The actual question about when to use one or the other is that you have to use the first form if you want to add a pointer to its own type inside it like so:

    typedef struct Foo { struct Foo* Child; ... } Foo;
    

    However, what I would prefer is to do that with a typedef like so:

    typedef struct Foo Foo;
    struct Foo {Foo* Child;};
    

提交回复
热议问题