< Previous | Contents | Next >
What happens when you increase an integer variable beyond its maximum value? It turns out you don’t generate an error. Instead, the value “wraps around” to the type’s minimum value. Next up, I demonstrate this phenomenon. First I assign score the largest value it can hold.
score = 4294967295;
Then I increment the variable.
þþscore;
As a result, score becomes 0 because the value wrapped around, much like a car odometer does when it goes beyond its maximum value (see Figure 1.7).
Decrementing an integer variable beyond its minimum value “wraps it around” to its maximum.
Figure 1.7
A way to visualize an unsigned int variable “wrapping around” from its maximum value to its minimum.
Hin t
Make sure to pick an integer type that has a large enough range for its intended use.