Why should we typedef a struct so often in C?

后端 未结 15 2929
無奈伤痛
無奈伤痛 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:06

    One other good reason to always typedef enums and structs results from this problem:

    enum EnumDef
    {
      FIRST_ITEM,
      SECOND_ITEM
    };
    
    struct StructDef
    {
      enum EnuumDef MyEnum;
      unsigned int MyVar;
    } MyStruct;
    

    Notice the typo in EnumDef in the struct (EnuumDef)? This compiles without error (or warning) and is (depending on the literal interpretation of the C Standard) correct. The problem is that I just created an new (empty) enumeration definition within my struct. I am not (as intended) using the previous definition EnumDef.

    With a typdef similar kind of typos would have resulted in a compiler errors for using an unknown type:

    typedef 
    {
      FIRST_ITEM,
      SECOND_ITEM
    } EnumDef;
    
    typedef struct
    {
      EnuumDef MyEnum; /* compiler error (unknown type) */
      unsigned int MyVar;
    } StructDef;
    StrructDef MyStruct; /* compiler error (unknown type) */
    

    I would advocate ALWAYS typedef'ing structs and enumerations.

    Not only to save some typing (no pun intended ;)), but because it is safer.

提交回复
热议问题