Nameless union inside a union

三世轮回 提交于 2019-12-06 20:16:07

问题


I'm reading some code and found something like the following:

typedef union {
    int int32;
    int boolean;
    time_t date;
    char *string;
    union {
        struct foo *a;
        struct foo *b;
        struct foo *c;
    };
} type_t;

From syntax point of view, the inner union {} can be removed and having *a, *b and *c directly inside the outer union {}. So what's the purpose the namelessly embedded union?


回答1:


Unnamed union/struct inside another union/struct is a feature of C11, and some compiler extensions (e.g, GCC).

C11 §6.7.2.1 Structure and union specifiers

13 An unnamed member whose type specifier is a structure specifier with no tag is called an anonymous structure; an unnamed member whose type specifier is a union specifier with no tag is called an anonymous union. The members of an anonymous structure or union are considered to be members of the containing structure or union. This applies recursively if the containing structure or union is also anonymous.

The advantage of this feature is that one can access its unnamed union field easier:

type_t x;

To access the field a, you can simply use x.a. Compare with the code without using this feature:

typedef union {
    int int32;
    int boolean;
    time_t date;
    char *string;
    union u{      //difference in here
    struct foo *a;
    struct foo *b;
    struct foo *c;
    };
} type_t;

type_t x;

You need to use x.u.a.

Related: unnamed struct/union in C




回答2:


I think the intended use-case is more “anonymous union inside a struct”, and the behavior of “anonymous union inside a union” being the same as a “flat” union is just an acceptable compromise for consistency.




回答3:


Allows the same pointer to be called a, b or c. Maybe there is some legacy code that can't agree on what name to use.



来源:https://stackoverflow.com/questions/22406229/nameless-union-inside-a-union

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!