Why should we typedef a struct so often in C?

后端 未结 15 3078
無奈伤痛
無奈伤痛 2020-11-21 23:58

I have seen many programs consisting of structures like the one below

typedef struct 
{
    int i;
    char k;
} elem;

elem user;

Why is i

15条回答
  •  醉梦人生
    2020-11-22 00:09

    the name you (optionally) give the struct is called the tag name and, as has been noted, is not a type in itself. To get to the type requires the struct prefix.

    GTK+ aside, I'm not sure the tagname is used anything like as commonly as a typedef to the struct type, so in C++ that is recognised and you can omit the struct keyword and use the tagname as the type name too:

    
        struct MyStruct
        {
          int i;
        };
    
        // The following is legal in C++:
        MyStruct obj;
        obj.i = 7;
    
    

提交回复
热议问题