What is signed integer overflow?

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

Since c is a (signedint 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 🙂

Leave a Comment