我正在查看 C11 草案,它说
An unnamed member of structure type with no tag is called an anonymous structure; an unnamed member of union type 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.
所以我构建了以下测试用例
// struct type with no tag
typedef struct {
unsigned char a;
unsigned char b;
// ... Some other members ...
unsigned char w;
} AToW;
union
{
AToW; // <- unnamed member
unsigned char bytes[sizeof(AToW)];
} myUnion;
Clang 和 GCC 都提示未命名的成员,说声明没有效果。是我做错了什么,还是他们根本不支持该功能?
最佳答案
不,那不是无名成员。
一个例子是:
struct outer {
int a;
struct {
int b;
int c;
};
int d;
};
包含成员的内部结构b
和 c
是 struct outer
的无名成员 .这位未具名成员的成员,b
和 c
, 被认为是包含结构的成员。
这对于包含 union 而不是包含结构可能更有用。特别是,它可用于定义类似于 Pascal 或 Ada 变体记录的内容:
enum variant_type { t_int, t_double, t_pointer, t_pair };
struct variant {
enum variant_type type;
union {
int i;
double d;
void *p;
struct {
int x;
int y;
};
};
};
这让您可以引用 i
, d
, 和 p
直接作为 struct variant
的成员对象,而不是为变体部分创建一个人工名称。如果某些变体需要多个成员,您可以在匿名 union 中嵌套匿名结构。
(它与 Pascal 和 Ada 的不同之处在于,在给定 type
成员的值的情况下,没有强制执行哪个变体处于事件状态的机制;这对你来说是 C。)
在您的示例中,AToW
是您之前定义的结构类型的 typedef。不允许裸体
AToW;
在结构定义的中间,除了你可以有一个裸体之外
int;
C11 添加了在另一个结构中定义嵌套匿名结构的功能,但只能在此时定义新的匿名结构类型。您不能拥有先前定义类型的匿名结构成员。语言可以被定义为允许它,并且语义(我认为)相当简单——但是定义两种不同的方法来做同一件事没有多大意义。 (对于上面的“struct”,读作“struct or union”。)
引用N1570 draft (这与发布的 2011 ISO C 标准非常接近),第 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.
结构说明符 由关键字 struct
组成,后跟一个可选的标识符(标签,在本例中省略),然后是一系列包含在 {
中的声明和 }
.在你的情况下,AToW
是类型名称,而不是结构说明符,因此不能用于定义匿名结构。
关于c - 这是 C11 匿名结构吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23527255/