以下代码:
#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);
}
Run Code Online (Sandbox Code Playgroud)
使用gcc正确编译和执行.如果试图转换一个常量,而且联合中没有合适的字段,则会产生错误消息.
但是,查看(C99)标准,我无法找到描述此行为的部分.因此,我的问题:
如果联合类型的字段具有兼容类型,那么C标准是否保证我可以将常量强制转换为联合类型?
或者,换句话说:
是
((val_t)10)一个有效的rvalue类型val_t?
了解其他编译器(或至少MS Visual C++)是否支持此行为也很有趣.有人知道吗?
编辑:转换为联盟是一个GCC扩展,所以使用它不是一个好主意.
感谢Maurits和Neil!我没想过用-pedantic检查!
小智 6
[neilb@GONERIL NeilB]$ gcc -Wall -pedantic sw.c
sw.c: In function 'main':
sw.c:11: warning: ISO C forbids casts to union type
sw.c:12: warning: ISO C forbids casts to union type
Run Code Online (Sandbox Code Playgroud)