Signed integer overflow vs Unsigned wrap
What you'll learn: Why the C compiler treats exceeding the limit of a signed integer as a critical error, while treating unsigned numbers as predictable circular loops.
The Odometer vs. The Contract
Imagine a car’s odometer. When it hits 999,999 and flips back to 000,000, it behaves predictably. In C, unsigned integers work exactly like this. They follow the rules of modular arithmetic. If you have an unsigned char at its maximum value of 255 and add 1, it is guaranteed to become 0. It is a "wrap-around."
Signed integers (like a standard int) are different. Because they use one bit to track whether a number is positive or negative, the math becomes trickier. If you push a signed integer past its maximum limit, the C standard does not say "it wraps around." Instead, it says the behavior is Undefined.
This isn't just a technicality; it’s a legal loophole for the compiler. If your code triggers signed overflow, the compiler is allowed to assume that code is impossible and might optimize it out of existence entirely.
Seeing the Difference
Look at how the compiler approaches these two loops. In the unsigned version, the behavior is a reliable loop. In the signed version, we enter a danger zone.
#include <stdio.h>
#include <limits.h>
int main() {
// 1. Unsigned Wrap (Defined Behavior)
unsigned int u = UINT_MAX;
u = u + 1;
printf("Unsigned max + 1 is: %u\n", u); // Always prints 0
// 2. Signed Overflow (Undefined Behavior)
int s = INT_MAX;
s = s + 1;
// DANGER: The compiler may assume 's' can never be greater than INT_MAX.
// It might delete the following print statement or crash the program.
printf("Signed max + 1 is: %d\n", s);
return 0;
}
Why does this matter?
Compilers are aggressive optimizers. If you write if (s + 1 > s), and s is a signed integer, the compiler might simplify that entire expression to true and remove the check entirely. Why? Because according to the C standard, s + 1 is never allowed to overflow, so the compiler assumes it will always be greater than s.
If your code actually causes that overflow, the program's logic breaks because the compiler stopped checking for the "impossible." With unsigned integers, the compiler is forced to respect the wrap-around, making them safer for calculations where you expect to hit the ceiling.
Key takeaway
Unsigned integers wrap around predictably like a clock, but signed integer overflow is a "forbidden" state that allows the compiler to break your program's logic.