Why should we typedef a struct so often in C?

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

    It's amazing how many people get this wrong. PLEASE don't typedef structs in C, it needlessly pollutes the global namespace which is typically very polluted already in large C programs.

    Also, typedef'd structs without a tag name are a major cause of needless imposition of ordering relationships among header files.

    Consider:

    #ifndef FOO_H
    #define FOO_H 1
    
    #define FOO_DEF (0xDEADBABE)
    
    struct bar; /* forward declaration, defined in bar.h*/
    
    struct foo {
      struct bar *bar;
    };
    
    #endif
    

    With such a definition, not using typedefs, it is possible for a compiland unit to include foo.h to get at the FOO_DEF definition. If it doesn't attempt to dereference the 'bar' member of the foo struct then there will be no need to include the "bar.h" file.

    Also, since the namespaces are different between the tag names and the member names, it is possible to write very readable code such as:

    struct foo *foo;
    
    printf("foo->bar = %p", foo->bar);
    

    Since the namespaces are separate, there is no conflict in naming variables coincident with their struct tag name.

    If I have to maintain your code, I will remove your typedef'd structs.

提交回复
热议问题