Underflow in unsigned types
What you'll learn: You will discover how unsigned variables behave when they drop below zero and why they suddenly jump to their maximum possible value.
The Odometer Effect
Imagine the mechanical odometer in an old car. If the display shows 000000 miles and you were somehow able to drive one mile in reverse, the gears wouldn't show a negative number. Instead, all the dials would roll back simultaneously to show 999999.
In C, unsigned variables work exactly like that odometer. Because an unsigned type is strictly forbidden from holding a negative sign, it cannot represent -1. When you try to subtract 1 from an unsigned zero, the value "wraps around" to the very top of its capacity. This event is called underflow.
Seeing Underflow in Code
Computer memory is finite. An unsigned int has a ceiling (the maximum value it can hold). When you go below floor-level (zero), you end up at the ceiling.
#include <stdio.h>
int main() {
// A typical 4-byte unsigned int maxes out at 4,294,967,295
unsigned int energy = 0;
printf("Current energy: %u\n", energy);
// Attempting to subtract from zero
energy = energy - 1;
printf("Energy after underflow: %u\n", energy);
return 0;
}
If you run this, the second line won't say -1. It will show a massive number like 4294967295. To the computer, the "bit pattern" for -1 and the bit pattern for the maximum possible unsigned number are identical; the only difference is how you tell C to interpret them.
Why This Matters
Underflow is a common source of "logic bugs." Imagine a game where a player's health is unsigned. If a monster deals 10 damage when the player only has 5 health left, the player won't die. Instead, their health will underflow and suddenly grant them billions of health points, making them effectively immortal.
When using unsigned types, always ensure your subtractions won't result in a value less than zero, or use a "signed" type if negative numbers are a possibility in your logic.
Key takeaway
When an unsigned variable goes below zero, it wraps around to its maximum possible value.