c++ - 在 cpp 中使用 union 的未定义行为?

标签 c++ unions

我正在使用 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/

相关文章:

作为 union 的 C++ 类

c++ - 我们可以访问一个不存在的联盟的成员吗?

c - c中的通用数据类型

c - fread_s 期间结构填充不正确

c++ - 保证复制省略的替代方法

c++ - 基访问派生的 friend

c++ - 使用 png++ 找出 png 颜色类型

c++ - 该算法最坏情况下的运行时间是多少?

c++ - 在常量表达式中访问 union 成员时出错

c++ - 如何使用 boost 和 Firebreath 从 python 中正确触发浏览器事件