Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why in C++ do static_cast<unsigned> of negative numbers differ if the number is constant or not

Tags:

c++

casting

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
like image 734
GreyMattR Avatar asked Nov 18 '19 16:11

GreyMattR


People also ask

What happens if you assign a negative number to an unsigned int?

You simply cannot assign a negative value to an object of an unsigned type. Any such value will be converted to the unsigned type before it's assigned, and the result will always be >= 0.

Can uint32_t be negative?

UInt32 stands for unsigned integer. 3. It can store negative and positive integers.

What is the point of static_cast?

The static_cast operator converts variable j to type float . This allows the compiler to generate a division with an answer of type float . All static_cast operators resolve at compile time and do not remove any const or volatile modifiers.

Can static_cast fail?

static_cast can't throw exception since static_cast is not runtime cast, if some cannot be casted, code will not compiles. But if it compiles and cast is bad - result is undefined.


1 Answers

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.

like image 100
Bathsheba Avatar answered Oct 05 '22 10:10

Bathsheba