仅用于澄清匿名struct 或匿名union。
C11
6.7.2.1 结构和联合说明符
一个未命名成员,其类型说明符是一个结构说明符
无标签称为匿名结构;一个未命名的成员,其类型
说明符是一个联合说明符,带有 no tag 被称为 anonymous
联合。匿名结构或联合的成员被考虑
成为包含结构或联合的成员。这适用
如果包含结构或联合也是匿名的,则递归。
C99 没有匿名结构或联合
简化:类型说明符 标识符 { 声明列表 } 标签 ;
-
类型说明符:
struct 或union;
-
标识符:可选,
struct 或 union 的自定义名称;
-
声明列表:成员、您的变量、匿名
struct 和匿名union
-
标签:可选。如果您在 Type-specifier 前面有
typedef,则 Tags 是别名,而不是 Tags。
只有当它没有标识符和标签并且存在于另一个struct或union中时,它才是匿名struct或匿名union。
struct s {
struct { int x; }; // Anonymous struct, no identifier and no tag
struct a { int x; }; // NOT Anonymous struct, has an identifier 'a'
struct { int x; } b; // NOT Anonymous struct, has a tag 'b'
struct c { int x; } C; // NOT Anonymous struct
};
struct s {
union { int x; }; // Anonymous union, no identifier and no tag
union a { int x; }; // NOT Anonymous union, has an identifier 'a'
union { int x; } b; // NOT Anonymous union, has a tag 'b'
union c { int x; } C; // NOT Anonymous union
};
typedef hell:如果你有typedef,标签部分不再是标签,它是该类型的别名。
struct a { int x; } A; // 'A' is a tag
union a { int x; } A; // 'A' is a tag
// But if you use this way
typedef struct b { int x; } B; // 'B' is NOT a tag. It is an alias to struct 'b'
typedef union b { int x; } B; // 'B' is NOT a tag. It is an alias to union 'b'
// Usage
A.x = 10; // A tag you can use without having to declare a new variable
B.x = 10; // Does not work
B bb; // Because 'B' is an alias, you have to declare a new variable
bb.x = 10;
下面的示例只是将struct 更改为union,工作方式相同。
struct a { int x; }; // Regular complete struct type
typedef struct a aa; // Alias 'aa' for the struct 'a'
struct { int x; } b; // Tag 'b'
typedef struct b bb; // Compile, but unusable.
struct c { int x; } C; // identifier or struct name 'c' and tag 'C'
typedef struct { int x; } d; // Alias 'd'
typedef struct e { int x; } ee; // struct 'e' and alias 'ee'