C++

WRAPPING AROUND A SIGNED INTEGER

A signed integer is different from an unsigned integer, in that half of the values you can represent 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 0 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 0. Listing 3.5 shows what happens when you add 1 to the maximum positive number in an unsigned short integer.

Listing 3.5. A demonstration of adding too large a number to a signed integer.

1: #include <iostream.h>

2: int main()

3: {

4: short int smallNumber;

5: smallNumber = 32767;

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:32767

small number:-32768

small number:-32767

Analysis: On line 4, smallNumber is declared this time to be a signed short integer (if you don’t explicitly say that it is unsigned, it is assumed to be signed). The program proceeds much as the preceding one, but the output is quite different. To fully understand this output, you must be comfortable with how signed numbers are represented as bits in a two-byte integer. For details, check Appendix C, "Binary and Hexadecimal."

The bottom line, however, is that just like an unsigned integer, the signed integer wraps around from its highest positive value to its highest negative value.

Back to Index