众所周知,最小的整数根据编译器的不同而不同,所以我有这样的问题: (int)-2147483648
的结果是什么?除以(int)-1
当你使用各种编译器时你会得到什么?比如VC6.0、VS2010等?
最佳答案
首先,我们假设我们处于 32-bit
中具有二进制补码表示的系统其中 INT_MIN
值与 -INT_MAX - 1
相同.
这个表达式:
(int) -2147483648 / (int) -1
相当于
(int) -2147483648 / -1
如-1
已经是 int
类型.
在 32-bit
二进制补码系统,其中 INT_MAX
是 2147483647
,值2147483648
类型为long
1) 因为它不能在 int
中表示。 -2147483648
的值也是 long
类型.
long
值-2147483648
可以用 int
表示,以及(int) -2147483648
整数转换后的值是 INT_MIN
.
原始表达式相当于(在我们的假设下):
INT_MIN / -1
这个表达式相当于INT_MAX + 1
这在 int
中是无法表示的。确实int
类型范围从 INT_MIN
至INT_MAX
。该表达式是整数溢出,整数溢出会调用 C 中未定义的行为。
<小时/> <子>(C99, 6.5p5) "If an exceptional condition occurs during the evaluation of an expression (that is, if the result is not mathematically defined or not in the range of representable values for its type), the behavior is undefined."
1) 我们隐含地假设LONG_MAX
是 > INT_MAX
,否则值为 2147483648
类型为long long
。
关于c++ - (int)-2147483648 除以 (int)-1 的结果,使用不同的编译器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14070524/