Why should we typedef a struct so often in C?

后端 未结 15 2909
無奈伤痛
無奈伤痛 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条回答
  • I don't think forward declarations are even possible with typedef. Use of struct, enum, and union allow for forwarding declarations when dependencies (knows about) is bidirectional.

    Style: Use of typedef in C++ makes quite a bit of sense. It can almost be necessary when dealing with templates that require multiple and/or variable parameters. The typedef helps keep the naming straight.

    Not so in the C programming language. The use of typedef most often serves no purpose but to obfuscate the data structure usage. Since only { struct (6), enum (4), union (5) } number of keystrokes are used to declare a data type there is almost no use for the aliasing of the struct. Is that data type a union or a struct? Using the straightforward non-typdefed declaration lets you know right away what type it is.

    Notice how Linux is written with strict avoidance of this aliasing nonsense typedef brings. The result is a minimalist and clean style.

    0 讨论(0)
  • 2020-11-22 00:24

    Turns out in C99 typedef is required. It is outdated, but a lot of tools (ala HackRank) use c99 as its pure C implementation. And typedef is required there.

    I'm not saying they should change (maybe have two C options) if the requirement changed, those of us studing for interviews on the site would be SOL.

    0 讨论(0)
  • 2020-11-22 00:25

    Using a typedef avoids having to write struct every time you declare a variable of that type:

    struct elem
    {
     int i;
     char k;
    };
    elem user; // compile error!
    struct elem user; // this is correct
    
    0 讨论(0)
提交回复
热议问题