将负的 const double 转换为 unsigned 结果为 0,而非常量 double 很好

Casting a negative const double to unsigned results in 0 while non-const double is fine

我有这个代码:

#include <iostream>

int main() {
    double val = -400.0;
    const double constVal = -400.0;
    std::cout << val << std::endl;
    std::cout << static_cast<unsigned>(val) << std::endl;
    std::cout << constVal << std::endl;
    std::cout << static_cast<unsigned>(constVal) << std::endl;

    return 0;
}

当我运行它时,这是输出:

-400
4294966896
-400
0

为什么会这样?适量的谷歌搜索在这件事上没有任何结果。

来自cppreference.com

A prvalue of floating-point type can be converted to a prvalue of any integer type. The fractional part is truncated, that is, the fractional part is discarded. If the value cannot fit into the destination type, the behavior is undefined (even when the destination type is unsigned, modulo arithmetic does not apply). If the destination type is bool, this is a boolean conversion (see below).

-400 不适合 unsigned,因此行为未定义。试图推理任何类型的一致性都是无用的。

由于这是未定义的行为,编译器在这种情况下可以为所欲为。通常,他们会做任何使其余(定义的)行为更容易编码的事情。尽管 popular sayings,编译器不太可能让恶魔从你的鼻子里飞出来,但你不应该期待任何特别的行为。