以下代码:
#include <stdio.h>
typedef union {
int n;
char *s;
} val_t;
int main(void) {
val_t v1,v2;
v1 = (val_t)"Hello World";
v2 = (val_t)10;
printf("%s %d\n", v1.s, v2.n);
return(1);
}
使用 gcc 正确编译和执行。如果尝试转换 union 中没有合适字段的常量,则会产生一条错误消息。
不过,查看 (C99) 标准时,我无法找到描述此行为的部分。因此,我的问题是:
Does the C standard guarantee that I can cast a constant to a union type, provided that the union type has a field with a compatible type?
或者,换句话说:
Is
((val_t)10)
a valid rvalue of typeval_t
?
了解其他编译器(或至少 MS Visual C++)是否支持此行为也很有趣。有人知道吗?
编辑: 转换为 union 是 GCC 扩展,因此使用它不是一个好主意。
感谢 Maurits 和 Neil!我没有考虑使用 -pedantic 来检查!
最佳答案
在GNU C language extensions强制转换为 union 被标记为对 C 标准的扩展。所以很可能您不会在 C99 或任何其他 C 标准中找到它。 IBM C 编译器也支持此扩展。
关于将常量转换为 union ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2146922/