写作然后根据C标准未定义阅读不同的工会成员?

参见英文答案 > Is type-punning through a union unspecified in C99, and has it become specified in C11?                                    4个
>            Can I assign a value to one union member and read the same value from another?                                    3个
我读到这个代码是根据c标准未定义但我无法找到原因.
它在gcc 8.1.0和clang-6.0中编译没有错误并打印1.

代码如下:

#include <stdio.h>

int main()
{
   union {
     int i;
     short s;
   } u;  
   u.i = 42;
   u.s = 1;

   printf("%d\n", u.i);
   return 0;
}
最佳答案
根据C11规范,§6.5.2.3注95:

If the member used to read the contents of a union object is not the same as the member last used to
store a value in the object, the appropriate part of the object representation of the value is reinterpreted
as an object representation in the new type as described in 6.2.6 (a process sometimes called ‘‘type
punning’’). This might be a trap representation.

这表示您正在执行的操作是允许的,但也暗示您读取的值可能不是您所期望的(例如,通过写入int成员并从float成员读取).

还有关于陷阱表示值的警告,在这种情况下,行为将是未定义的.对于two’s complement系统(这是过去几十年中绝大多数计算机),这不是整数值的问题.

在你的情况下,结果将在很大程度上取决于平台endianness.要么你得到你写的值(1),要么得到0.

转载注明原文:写作然后根据C标准未定义阅读不同的工会成员? - 代码日志