Using an anonymous struct vs a named struct with typedef

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

    One time where the former is required is if you're making a linked list:

    typedef struct list {
        int data;
        struct list *next;
    } list;
    

    The typedef list is not visible inside of the struct definition, so you need to use the actual struct name to create a pointer to it.

    If you don't have such a structure, you can use either one.

    What you shouldn't do however is use a tag name that starts with an underscore, i.e.:

    typedef struct _list {
        int data;
        struct list *next;
    } list;
    

    Because names starting with a underscore are reserved by the implementation.

提交回复
热议问题