I have this code:
#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;
}
When I run it, this is the output:
-400
4294966896
-400
0
Why does this happen? A moderate amount of Googling shows nothing on this matter.
From 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 cannot fit in an unsigned
, therefore the behavior is undefined. Trying to reason about any type of consistency is useless.
Since this is undefined behavior, the compiler may do anything it wants in this situation. Normally, they do whatever makes the rest of their (defined) behavior easier to code. Despite popular sayings, the compiler is unlikely to make demons fly out of your nose, but one shouldn't expect any behavior in particular.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With