Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

c - What is signed integer overflow?

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
", c);
}

Can someone explain what that means?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your while condition will always be true, meaning the loop will run forever, adding 1 to c in each iteration.

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".

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.

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...

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 :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...