我想知道是否可以在 ANSI C 中声明匿名结构。我拥有的代码是:
struct A
{
int x;
};
struct B
{
struct A;
int y;
};
当我编译它时,我得到: 警告:声明没有声明任何东西
我已经读过该标志-fms-extensions
可以解决问题,但是它只能在 Windows 系统上运行,因为它产生:
警告:匿名结构是 Microsoft 扩展 [-Wmicrosoft]
我可以使用任何 ANSI 等效扩展吗?
我想知道是否可以在 ANSI C 中声明匿名结构。我拥有的代码是:
struct A
{
int x;
};
struct B
{
struct A;
int y;
};
当我编译它时,我得到: 警告:声明没有声明任何东西
我已经读过该标志-fms-extensions
可以解决问题,但是它只能在 Windows 系统上运行,因为它产生:
警告:匿名结构是 Microsoft 扩展 [-Wmicrosoft]
我可以使用任何 ANSI 等效扩展吗?
在 ANSI C 中获得几乎此功能的一个技巧是使用适当的宏:
struct A {
int x;
};
struct B {
struct A A_;
int y;
};
#define bx A_.x
然后你可以简单地做
struct B foo, *bar;
foo.bx;
bar->bx;
但是在 C11 中,支持匿名结构,你可以简单地做
struct B {
struct {
int x;
};
int y;
}
但遗憾的是没有
struct A {
int x;
};
struct B
{
struct A;
int y;
};
由于必须在结构内声明匿名结构,因此它是匿名的。
有关 C11 中匿名成员的更多详细信息,请参阅此答案。
可以声明匿名结构和联合。ISO C11 添加了这个特性,GCC 允许它作为扩展。
C11 节 §6.7.2.1 第 13 段:
类型说明符是没有标记的结构说明符的未命名成员称为匿名结构;类型说明符是没有标记的联合说明符的未命名成员称为匿名联合。匿名结构或联合的成员被视为包含结构或联合的成员。如果包含结构或联合也是匿名的,这将递归地应用。
19 以下说明了匿名结构和联合:
struct v {
union { // anonymous union
struct { int i, j; }; // anonymous structure
struct { long k, l; } w;
};
int m;
} v1;
v1.i = 2; // valid
v1.k = 3; // invalid: inner structure is not anonymous
v1.w.k = 5; // valid
现在b
只需使用即可访问foo.b
。
我想你想要这样的东西:
struct B {
struct {
int x;
} A;
int y;
};
你可以这样做:
struct B b;
b.A.x = 5;
printf( "%d\n", b.A.x );