< previous page page_36 next page >

Page 36
When an unsigned integer reaches its maximum value, it wraps around and starts over, much as a car odometer might. Listing 3.4 shows what happens if you try to put too large a value into a short integer.
LISTING 3.4 DEMONSTRATES PUTTING TOO LARGE A VALUE IN ANunsigned INTEGER

d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
1:   #include <iostream.h>
2:   int main()
3:   {
4:      unsigned short int smallNumber;
5:      smallNumber = 65535;
6:      cout << small number: << smallNumber << endl;
7:      smallNumber++;
8:      cout << small number: << smallNumber << endl;
9:      smallNumber++;
10:     cout << small number: << smallNumber << endl;
11:     return 0;
12:  }

Output:
small number: 65535
small number: 0
small number: 1
Analysis: On line 4 smallNumber is declared to be an unsigned short int, which on my computer is a two-byte variable able to hold a value between 0 and 65,535. On line 5 the maximum value is assigned to smallNumber, and it is printed on line 6.
On line 7 smallNumber is incremented; that is, 1 is added to it. The symbol for incrementing is ++ (as in the name C++an incremental increase from C). Thus, the value in smallNumber would be 65,536. But unsigned short integers can't hold a number larger than 65,535, so the value is wrapped around to 0, which is printed on line 8.
On line 9 smallNumber is incremented again, and its new value, 1, is printed.
Wrapping Around a signed Integer
A signed integer is different from an unsigned integer in that half of its values are negative. Instead of picturing a traditional car odometer, you might picture one that rotates up for positive numbers and down for negative numbers. One mile from zero is either 1 or -1. When you run out of positive numbers, you run right into the largest negative numbers and then count back down to zero. Listing 3.5 shows what happens when you add 1 to the maximum positive number in an unsigned short integer.

 
< previous page page_36 next page >

If you like this book, buy it!