< Previous | Contents | Next >

Dealing with Integer Wrap

Around

What happens when you increase an integer variable beyond its maximum value? It turns out you dont generate an error. Instead, the value wraps aroundto the types 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 aroundto its maximum.

Working with Constants 29



image

Figure 1.7

A way to visualize an unsigned int variable “wrapping around” from its maximum value to its minimum.


Hin t

image

Make sure to pick an integer type that has a large enough range for its intended use.

image