我正在阅读一些代码,发现如下内容:
typedef union {
int int32;
int boolean;
time_t date;
char *string;
union {
struct foo *a;
struct foo *b;
struct foo *c;
};
} type_t;
Run Code Online (Sandbox Code Playgroud)
从语法的角度来看,内部联合{}可以被移除并且在外部联合{}内直接具有*a,*b和*c.那无名嵌入式联盟的目的是什么?
另一个union/struct中未命名的union/struct是C11的一个特性,以及一些编译器扩展(例如,GCC).
C11§6.7.2.1结构和联合说明符
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;
Run Code Online (Sandbox Code Playgroud)
To access the field a
,您只需使用即可x.a
.与代码比较而不使用此功能:
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;
Run Code Online (Sandbox Code Playgroud)
你需要使用x.u.a
.
允许同一个指针被称为 a、b 或 c。也许有一些遗留代码无法就使用什么名称达成一致。