为什么它在-2147483648和(int)-2147483648之间不同 [英] Why it is different between -2147483648 and (int)-2147483648

查看:603
本文介绍了为什么它在-2147483648和(int)-2147483648之间不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在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 ++中未定义的行为,但是你的编译器接受它作为扩展。)取消无符号整数值是可能的,但结果是另一个无符号整数值,从来不是负数。 Negating 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.

这篇关于为什么它在-2147483648和(int)-2147483648之间不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆