Sams Teach Yourself C++ in 21 Days

(singke) #1
positive and negative numbers, and thus their maximum value is only half that of the
unsigned.
Although unsigned longintegers can hold an extremely large number (4,294,967,295),
that is still quite finite. If you need a larger number, you’ll have to go to floator
double, and then you lose some precision. Floats and doubles can hold extremely large
numbers, but only the first seven or nine digits are significant on most computers. This
means that the number is rounded off after that many digits.
Shorter variables use up less memory. These days, memory is cheap and life is short.
Feel free to use int, which is probably four bytes on your machine.

Wrapping Around an unsignedInteger............................................................


Thatunsigned longintegers have a limit to the values they can hold is only rarely a
problem, but what happens if you do run out of room?
When an unsignedinteger 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.

LISTING3.4 A Demonstration of Putting Too Large a Value in an unsigned shortInteger
1: #include <iostream>
2: int main()
3: {
4: using std::cout;
5: using std::endl;
6:
7: unsigned short int smallNumber;
8: smallNumber = 65535;
9: cout << “small number:” << smallNumber << endl;
10: smallNumber++;
11: cout << “small number:” << smallNumber << endl;
12: smallNumber++;
13: cout << “small number:” << smallNumber << endl;
14: return 0;
15: }

small number:65535
small number:0
small number:1
On line 7,smallNumberis declared to be an unsigned short int, which on a
Pentium 4 computer running Windows XP is a two-byte variable, able to hold a
value between 0 and 65,535. On line 8, the maximum value is assigned to smallNumber,
and it is printed on line 9.

OUTPUT


54 Day 3


ANALYSIS
Free download pdf