Using an anonymous struct vs a named struct with typedef

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

    It doesn't really matter much. If you use the tagged form you can have pointers to struct Foo inside struct Foo (AKA Bar)

    typedef struct Foo{
      int a;
      struct Foo *foop;
    } Bar;
    

    but there's no way to do that with the second form

    typedef struct {
      int a;
      //Baz *p; not valid here since Baz isn't a typename yet
    } Baz;
    

    Some codebases prefer not to use typedefs at all and simply spell out struct Foo with the struct keyword every time.

    Also, with the first form, you can refer to the type either via the tag (struct Foo) or with typedefs (Bar or any future/previous typedefs (you can do typedef struct Foo PreviousTypedef; before you provide the definition).

    With the second form, on the other hand, you can only use the Baz typedef and possible future typedefs (you can't forward-typedef the struct since it doesn't have a tag).

    (Note that typedef doesn't really define types in C. The struct optional_tag { /*...*/ } part does. Rather, typedef provides type aliases (so perhaps it should have been named typealias).)

提交回复
热议问题