我正在使用 C++ 开发 union , 以下是代码片段:
#include<iostream>
using namespace std;
typedef union myunion
{
double PI;
int B;
}MYUNION;
int main()
{
MYUNION numbers;
numbers.PI = 3;
numbers.B = 50;
cout <<" numbers.PI :" << numbers.PI << endl;
if(numbers.PI == 3.0)
{
cout <<"True";
if(numbers.B == 50)
{
cout <<" numbers.PI :" << numbers.PI << endl;
cout <<" numbers.B :" << numbers.B << endl;
}
}
return 0;
}
输出是:
numbers.PI :3
numbers.PI 的偶数值已经设置为 3,第一个“if”条件屈服于 false。 这种行为的原因是什么?
最佳答案
理由就是没有理由。
您的代码调用了未定义的行为,因为您正在设置 union 的 B
成员:
numbers.B = 50;
但设置后立即读出其他成员 PI
:
cout <<" numbers.PI :" << numbers.PI << endl;
也许您混淆了 union 和结构 - 除非 float 3
和整数 50
在您的体系结构(这不太可能),只有当您使用 struct
时,您期望程序的行为才是合理的。
(union
成员驻留在内存中的同一位置 - 设置一个也会覆盖另一个。这对于 struct
而言并非如此,它存储了每个成员在不同的内存位置。)
关于c++ - 在 cpp 中使用 union 的未定义行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18480741/