为什么以下程序会发生溢出? [英] Why may an overflow occur in the following program?
问题描述
void main () {
int i;
if (i < 0) { i = -i; };
}
任何人都可以帮助我理解为什么在上述程序中可能出现溢出?
Can anyone help me to understand why an overflow may occur in the above program?
推荐答案
可能会发生溢出,因为二进制补码中的整数表示范围不对称:最小负数的大小可以表示的是可以表示的最高正数的大小加一。例如,在32位系统上,值为 -2,147,483,648
和 2,147,483,647
。这就是为什么否定 -2,147,483,648
会导致溢出:否定的结果,正值 2,147,483,648
,无法表示在相同大小的 int
中。
An overflow may occur because the range of integer representation in two's complement is not symmetric: the magnitude of the smallest negative number that can be represented is the magnitude of the highest positive number that can be represented, plus one. For example, on a 32-bit system the values are -2,147,483,648
and 2,147,483,647
. That's why negating -2,147,483,648
would result in an overflow: the result of negation, a positive value 2,147,483,648
, cannot be represented in an int
of the same size.
注意这个问题的反面不是这样的:否定正面数字不会导致溢出:
Note that the inverse of this problem is not true: negating a positive number would not result in an overflow:
if (i > 0) { i = -i; } // No overflow here
这篇关于为什么以下程序会发生溢出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!