Using an anonymous struct vs a named struct with typedef

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

    A lot of other people are focusing on the self referential aspect of this, but another reason to avoid doing this is that due to the lack of namespaces in C. In some circles it is standard practice to not typedef structs to avoid struct qualifier and instead refer to structs with the full specifier (eg void foo(struct Foo* foo_ptr)). So if you wanted to maintain such a style, you wouldn't have the option to abuse anonymous structs, so this:

    typedef struct {
      int a;
    } Bar;
    
    Bar bar1 = {5};
    

    should always instead be

    struct Bar{
      int a;
    };
    
    struct Bar bar1 = {5};
    

    otherwise you couldn't even compile bar1's instantiation with out typedefing away the struct qualifier

提交回复
热议问题