Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 551
user2725742 Avatar asked Oct 20 '25 00:10

user2725742


1 Answers

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.

like image 150
JohnFilleau Avatar answered Oct 22 '25 14:10

JohnFilleau