如何在不命名的情况下访问工会成员?

How to access a member of a union without naming it?

我有一些代码与下面的非常相似

struct T {
    union {
        unsigned int x;
        struct {
            unsigned short xhigh;
            unsigned short xlow;
        };
    } x;
    /* ...repeated a handful of times for different variables in T... */
};

这完全符合您的预期:它允许我声明类型为 struct T 的变量并访问 t.x.xt.x.xhight.x.xlow。到目前为止一切顺利。

但是,我真的很喜欢它,如果我可以在想要访问联合的值作为 [=17] 的常见情况下只做 t.x =] 数量,但保留独立访问高阶和低阶部分的能力,无需诉诸位屏蔽和移位,也无需调用未定义的行为。

在 C 中可以吗?

如果可以的话,声明的C语法是什么?

当我尝试简单地访问 t.x 而不是 t.x.x 的天真方法时,我收到警告消息,例如(这个特定的消息来自 printf() 调用):

cc -ansi -o test -Wall test.c
test.c: In function ‘my_function’:
test.c:13:2: warning: format ‘%X’ expects argument of type ‘unsigned int’, but argument 2 has type ‘const union <anonymous>’ [-Wformat]

使用 -std=c11 而不是 -ansi 会产生相同的警告。

如果您可以使用匿名结构(它们都是 C11 功能或编译器扩展),匿名联合是一回事。

正如您使用没有名称的 struct 将其成员注入联合命名空间一样,您也可以使用没有名称的 union 将其成员注入封闭的命名空间命名空间。像这样:

struct T {
    union {
        unsigned int x;
        struct {
            unsigned short xhigh;
            unsigned short xlow;
        };
    }; /* <-- no name here */

    /* ...repeated a handful of times for different variables in T... */
};

你只需要确保 none 的注入名称与其他注入名称或那里的常规名称冲突,否则将无法编译。


但有一个问题:您似乎依赖 "fact",即 unsigned short 的大小是 unsigned int 的一半,并且这些类型是大端。但是,如果这就是您的系统上发生的情况,那很好。如果没有,我建议你重新考虑结构。