Is typedef ever required in C?

前端 未结 15 2837
夕颜
夕颜 2021-02-13 14:19

Typedef is very useful for portable names, tag names (typedef struct foo Foo;) and keeping complicated (function) declarations readable (typedef int (*cmpfunc

相关标签:
15条回答
  • 2021-02-13 14:52

    We use typedef to at work keep code platform independent. Like for example, we do something like

    typedef unsigned char SHORT;
    

    this makes code more readable and easy to port.

    0 讨论(0)
  • 2021-02-13 14:55

    From wikipedia:

    typedef is a keyword in the C and C++ programming languages. The purpose of typedef is to assign alternative names to existing types, most often those whose standard declaration is cumbersome, potentially confusing, or likely to vary from one implementation to another.1

    Based on that definition, no it's never required as you can always just write out the expanded form. However, there may be macro definitions which choose a typedef to use based on platform or something else. So always using the expanded form may not be very portable.

    0 讨论(0)
  • 2021-02-13 14:55

    I know of no cases where typedef is explicitly needed in C.

    0 讨论(0)
  • 2021-02-13 14:56

    doesn't 'extremely useful' mean requied?

    not even hard for me to think about a project with struct for each struct member,pointer,arguement,and so on.

    0 讨论(0)
  • 2021-02-13 14:59

    Individual programmers are not required to create their own typedefs. There's no universal rule saying I can't write things like

    int *(*(*x())[5])();
    

    if I so desire (although my company's coding standards may frown on it).

    They're all over the standard library, however (FILE, size_t, etc.), so you really can't avoid using typedef names.

    0 讨论(0)
  • 2021-02-13 15:02

    Without typedef, you have to use the keyword struct everytime if you use a struct in declarations. With typedef, you can omit this.

    struct Person
    {
      char * name;
    };
    
    struct Person p; /* need this here*/
    
    typedef struct _Person
    {
      char * name;
    } Person;
    
    Person p; /* with typedef I can omit struct keyword here */
    
    0 讨论(0)
提交回复
热议问题