Why is (2147483648>0) true in C++?

Asked 2 years ago, Updated 2 years ago, 127 views

At 32 bits, -2147483648 is the smallest value that the int type can express. But I think there is an overflow in the if statement.

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

Result: true

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

Result: false

Why do the two have different results? I'm using a VC!

c++ overflow

2022-09-22 12:30

1 Answers

-2147483648 is not a number. C++ does not support negative literal. -2147483648 is a positive 2147483648 with a unary operator -.

2147483648 is too large for the int type on the person's platform. If long int could have saved a larger range on the platform, the compiler would have considered 2147483648 as long int (C++11 and above) long int and output false

Maybe long int and int are the same size on the platform The overflow must have occurred because there is no signed integer type that can express the constant 2147483648.

In this case, there's no specific rule Depending on the implementation, it can be interpreted as either positive or negative. If 2147483648 is interpreted as a negative number, -2147483648 becomes positive and becomes True


2022-09-22 12:30

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.