作者:key920721 | 来源:互联网 | 2023-02-03 13:10
void main () {
int i;
if (i <0) { i = -i; };
}
Can anyone help me to understand why an overflow may occur in the above program?
任何人都可以帮我理解为什么在上述程序中可能出现溢出?
3 个解决方案
13
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.
可能会发生溢出,因为二进制补码中的整数表示范围不对称:可以表示的最小负数的大小是可以表示的最高正数的大小加一。例如,在32位系统上,值为-2,147,483,648和2,147,483,647。这就是为什么否定-2,147,483,648会导致溢出:否定的结果,正值2,147,483,648,不能用相同大小的int表示。
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