Is typedef ever required in C?

前端 未结 15 2743
夕颜
夕颜 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 15:03

    No.

    A typedef does not create a truely new type as say a class in C++, it merely creates a type alias - a single identifier for something else that already exists. In a typedef, you define no new behaviour, semantics, conversions or opeators.

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

    it is definitely required, a good example is size_t which is typedef'd on various platforms.

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

    A typedef is, by definition, an alias. As such, you always could replace the alias with the actual type. It wouldn't be an alias otherwise.

    That doesn't mean avoiding typedef would be a good idea.

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

    The keyword typedef is definitely needed in test suites that check a C compiler for ISO-C compliance.

    In code that is not explicitly supposed to use typedef (like the test suite above) it is often very helpful but never essential because it only establishes an alias to another type. It does not create a type.

    Finally, I would not count things like avoiding a compiler limit on preprocessed source file size through the abbreviation typedefs can offer.

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

    The offsetof() macro requires a structname and a membername, and thus cannot be used with inline struct definitions. Well, maybe on your implementation it can, but it isn't guaranteed by the C standard.

    Update: As pointed out in the comments, this is possible:

    struct blah { int a; int b; };
    x = offsetof(struct blah, a); // legal
    

    But inlining the struct definition is not:

    x = offsetof(struct {int a; int b;}, a); // illegal
    

    The former does not contain the keyword typedef, but inlining the struct definition is not possible either. Which version is indicated by "simple writing out the derived type" is unclear.

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

    To me, typedef provides abstraction. It keeps my code clean and very easy to understand. You can live without typedef just like you can live without all high level languages and sticking with assembly or machine language.

    0 讨论(0)
提交回复
热议问题