结构中的匿名联合不在 c99 中? [英] Anonymous union within struct not in c99?

查看:26
本文介绍了结构中的匿名联合不在 c99 中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我遇到的问题的非常简化的代码:

<前>枚举 node_type {t_int, t_double};结构 int_node {整数值;};结构双节点{双倍价值;};结构节点{枚举 node_type 类型;联合{结构 int_node int_n;struct double_node double_n;};};int main(void) {结构 int_node i;i. 值 = 10;结构节点 n;n.type = t_int;n.int_n = i;返回0;}

我不明白的是:

<前>$ cc us.c$ cc -std=c99 us.cus.c:18:4: 警告:声明没有声明任何东西us.c:在函数‘main’中:us.c:26:4: 错误:struct node"没有名为int_n"的成员

使用没有 -std 选项的 GCC 编译上面的代码没有任何问题(并且类似的代码运行良好),但似乎 c99 不允许这种技术.为什么会这样,是否有可能使 c99(或 c89c90)兼容?谢谢.

解决方案

匿名联合是 GNU 扩展,不是任何标准版本的 C 语言的一部分.对于 c99+GNU 扩展,您可以使用 -std=gnu99 或类似的东西,但最好编写适当的 C,而不是依赖于只提供语法糖的扩展......

在 C11 中添加了匿名联合,因此它们现在是该语言的标准部分.大概 GCC 的 -std=c11 可以让你使用它们.

here is very simplified code of problem I have:

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;
}

And what I don't undestand is this:

$ 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 without -std option compiles code above without any problems (and the similar code is working pretty well), but it seems that c99 does not permit this technique. Why is it so and is it possible to make is c99 (or c89, c90) compatible? Thanks.

解决方案

Anonymous unions are a GNU extension, not part of any standard version of the C language. You can use -std=gnu99 or something like that for c99+GNU extensions, but it's best to write proper C and not rely on extensions which provide nothing but syntactic sugar...

Edit: Anonymous unions were added in C11, so they are now a standard part of the language. Presumably GCC's -std=c11 lets you use them.

这篇关于结构中的匿名联合不在 c99 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆