什么是有符号整数溢出? [英] What is signed integer overflow?
问题描述
我正在从CS50学习C。当我运行代码时,它会显示有符号整数溢出。
I'm learning C from CS50. When I run my code, it says 'signed integer overflow'.
#include <stdio.h>
#include <cs50.h>
int main(void)
{
int x = 41;
int c = 0;
while(x>=25)
{
c = c+1;
}
printf("%i\n", c);
}
有人可以解释这是什么意思吗?
Can someone explain what that means?
推荐答案
您的while条件始终为true,这意味着循环将永远运行,在每个 c
中加1
Your while condition will always be true, meaning the loop will run forever, adding 1 to c
in each iteration.
由于 c
是一个( signed
) int
表示它将缓慢递增至最大值,此后下一个增量将为UB(未定义行为)。在此特定的UB中,许多计算机的作用是将 c
设为负数,我想这不是您想要的。发生这种情况是由于一种称为有符号整数溢出的现象。
Since c
is a (signed
) int
it means it will increment slowly to its max value, and after that the next increment would be UB (undefined behavior). What many machines will do in this specific UB is to turn c
negative, which I guess is not what you wanted. This happens due to a phenomenon called "signed integer overflow".
我们假设32位 int
并使用 two的补码。 signed int
在二进制 sign位中看起来像这样(0表示正,1表示负)| 31位
。零看起来像 000 ... 00
,一个看起来像 000 ... 01
,依此类推。
Let's assume 32-bit int
and using two's complement. A signed int
will look like this in binary sign bit (0 for positive, 1 for negative) | 31 bits
. zero will look like 000...00
, one like 000...01
and so on.
最大签名整数将看起来像 0111 ... 11
( 2,147,483,647 )。在此数字上加1时,您会得到 100 ... 000
,该符号翻转了符号位,现在将导致负数。再加上1将导致 100 ... 001
再次在符号位上表示其仍为负...
Max signed int will look like 0111...11
(2,147,483,647). When adding 1 to this number you'll get 100...000
which flipped the sign bit which will now result in a negative number. Adding another 1 to this will result in 100...001
which again has the sign bit on meaning it is still negative...
将 c
声明为未签名将确保 c
保持非负数。另外,以 while(x--> = 25)
结束循环也是一个好主意:)
Declaring c
as unsigned would ensure c
remains non-negative. Also, making the loop end with while(x-- >= 25)
could also be a good idea :)
这篇关于什么是有符号整数溢出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!