C++ 将 NAN 值分配给 union 内的 float

标签 c++ nan unions

我想了解一个奇怪的行为。我有以下代码:

    union floatInt
    { 
        float f;
        unsigned int l;
    };

    floatInt A, B;

    A.l = 0xFFA70B56;
    B.f = A.f;

    std::cout << std::hex << B.l << std::endl;

这工作正常,除了在 1 个配置中:非 Debug模式下的 Linux,然后我得到这个结果:ffe70b56

而且我真的不明白为什么值发生了变化。我已经通过几点来理解这一点:

  1. cppreference/union指定

    It's undefined behavior to read from the member of the union that wasn't most recently written. Many compilers implement, as a non-standard language extension, the ability to read inactive members of a union.

    但是如果我们不能使用其他成员, union 的目的是什么?而且,它指向相同的内存位置,所以应该不会不同。

  2. 我使用的值 (0xFFA70B56) 是 IEEE 754 标准中的 NAN。那么,当它影响到另一个变量时,是否可以将其解释并更改为另一个 NAN 值,如 0xFFE70B56?
  3. 如果我将 B 声明为 volatile,则错误消失。请注意,该变量未在代码中的其他任何地方使用。那么它与编译器优化有关吗?

最佳答案

But what would be the purpose of a union if we cannot use the other members?

union的目的是在不同的时间使用相同的内存区域存储不同的对象,从而节省内存。

floatInt 占用的内存与float 变量占用的内存相同。 如果您的目标是使用 union ,我建议添加一个 bool 元素来跟踪使用了两个元素中的哪一个。

如果你想同时使用这两个属性,你应该使用 struct 或(我们在 c++ 中)class

有关 union 的更多信息,请阅读 here

关于C++ 将 NAN 值分配给 union 内的 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39979696/

相关文章:

c - union 的这种行为背后的逻辑是什么?

c - union 作为 C 中的结构变量

python - 多种条件下的 Pandas 面具

JavaScript - Infinity 和 NaN 应该是数字吗?

c++ - mov + mfence在NUMA上安全吗?

c++ - 为什么当我进入退出条件时程序打印两次默认条件而不是退出 while 循环?

python - 构建 NetworkX 图时避免使用 NaN 属性

c++ - 在这种情况下, union 成员的成员会调用自己的析构函数吗?

c++ - 将 libsvm 模型结构从 matlab 保存到可以在 C++ 中读取的 .model 文件

c++ - 保存命令行参数并对其进行类型转换