GreyMattR
GreyMattR

Reputation: 335

Why in C++ do static_cast<unsigned> 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

Upvotes: 29

Views: 1606

Answers (1)

Bathsheba
Bathsheba

Reputation: 234685

The behaviour of your program is undefined: the C++ standard does not define the conversion of a negative floating point type to an unsigned type.

(Note the familiar wrap-around behaviour only applies to negative integral types.)

So therefore there's little point in attempting to explain your program output.

Upvotes: 28

Related Questions