(-2147483648> 0) returns true in C++?

-2147483648 is the smallest integer for integer type with 32 bits, but it seems that it will overflow in the if(...) sentence:

if (-2147483648 > 0)
    std::cout << "true";
else
    std::cout << "false";

This will print true in my testing. However, if we cast -2147483648 to integer, the result will be different:

if (int(-2147483648) > 0)
    std::cout << "true";
else
    std::cout << "false";

This will print false.

I’m confused. Can anyone give an explanation on this?


Update 02-05-2012:

Thanks for your comments, in my compiler, the size of int is 4 bytes. I’m using VC for some simple testing. I’ve changed the description in my question.

That’s a lot of very good replys in this post, AndreyT gave a very detailed explanation on how the compiler will behave on such input, and how this minimum integer was implemented. qPCR4vir on the other hand gave some related “curiosities” and how integers are represented. So impressive!

4 Answers
4

Leave a Comment