首页 > 解决方案 > Why in C++ do static_cast of negative numbers differ if the number is constant or not

问题描述

What's the C++ rules that means equal is false?. Given:

float f {-1.0};
bool equal = (static_cast<unsigned>(f) == static_cast<unsigned>(-1.0));

E.g. https://godbolt.org/z/fcmx2P

#include <iostream>

int main() 
{
          float   f {-1.0};
    const float  cf {-1.0};

    std::cout << std::hex;
    std::cout << " f" << "=" << static_cast<unsigned>(f) << '\n';
    std::cout << "cf" << "=" << static_cast<unsigned>(cf) << '\n';

    return 0;
}

Produces the following output:

 f=ffffffff
cf=0

标签: c++casting

解决方案


您的程序的行为是未定义的:C++ 标准没有定义负浮点类型unsigned类型的转换。

(请注意,熟悉的环绕行为仅适用于负整数类型。)

因此,尝试解释您的程序输出没有什么意义。


推荐阅读