这是我遇到的问题的非常简化的代码:
enum node_type {
t_int, t_double
};
struct int_node {
int value;
};
struct double_node {
double value;
};
struct node {
enum node_type type;
union {
struct int_node int_n;
struct double_node double_n;
};
};
int main(void) {
struct int_node i;
i.value = 10;
struct node n;
n.type = t_int;
n.int_n = i;
return 0;
}
我不明白的是:
$ cc us.c
$ cc -std=c99 us.c
us.c:18:4: warning: declaration does not declare anything
us.c: In function ‘main’:
us.c:26:4: error: ‘struct node’ has no member named ‘int_n’
Using GCC
没有-std
选项编译上面的代码没有任何问题(并且类似的代码运行得很好),但似乎c99
不允许使用这种技术。为什么会这样以及是否可以做到c99
(or c89
, c90
) 兼容的?谢谢。
匿名联合是 GNU 扩展,不属于任何 C 语言标准版本的一部分。您可以对 c99+GNU 扩展使用 -std=gnu99 或类似的东西,但最好编写正确的 C 并且不要依赖于只提供语法糖的扩展...
Edit:C11 中添加了匿名联合,因此它们现在已成为该语言的标准部分。大概是海湾合作委员会的-std=c11
让您使用它们。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)