为什么 -2147483648 和 (int)-2147483648 不同

2022-01-14 00:00:00 integer overflow c++

当我在Windows7 x64下运行以下代码,使用MinGW的GCC编译时,结果似乎下溢:

When I run the following code under Windows7 x64, compiled with GCC of MinGW, the result seems to be underflowed:

cout<<-2147483648 ;    //Output: 2147483648

但是当我将它分配给一个整数变量时,或者只是将它转换为 int 类型:

but when I assigned it to a integer variable, or just simply convert it to the int type :

cout<<(int)-2147483648 ; //Output: -2147483648 

那么,我之前的代码版本有什么问题?不是int类型吗?或者整数的下限到底是多少?非常感谢.

So, what's wrong with the previous version of my code? Istn't it the type int? or what the lower bound the Integer is exactly? Many thanks.

推荐答案

2147483648 在您的系统上不适合 int 或 long,因此它被视为 unsigned long 类型的常量.(正如 ouah 在评论中指出的那样,它在标准 C++ 中是未定义的行为,但您的编译器将其作为扩展接受.)对无符号整数值取反是可能的,但会产生另一个无符号整数值,而不是负数.否定 2147483648UL 会产生 2147483648UL(假设与您的系统一样,unsigned long 是 32 位类型).

2147483648 doesn't fit into an int or a long on your system, so it's treated as a constant of type unsigned long. ( as ouah pointed out in the comments, it's undefined behaviour in standard C++, but your compiler accepts it as an extension.) Negating an unsigned integer value is possible, but results in another unsigned integer value, never a negative number. Negating 2147483648UL produces 2147483648UL (assuming, as is the case on your system, that unsigned long is a 32 bit type).

将其转换为 int 会产生实现定义的结果,通常是您看到的结果,但不一定.你可以通过写-2147483647 - 1得到你想要的结果而不需要任何转换.

Casting that to int produces an implementation-defined result, commonly the result you see, but not necessarily. You can get the result you want without any conversions by writing -2147483647 - 1.

相关文章