|
|
 |
|
|
|
|
11: Length = 10;
12: USHORT Area = Width * Length;
13: cout << Width: << Width << \n;
14: cout << Length: << Length << endl;
15: cout << Area: << Area <<endl;
16: return 0;
17: } |
|
|
|
|
|
|
|
|
Width: 5
Length: 10
Area: 50 |
|
|
|
|
|
|
|
|
On some compilers, this code will issue a warning that the conversion may lose significant digits. This is because the product of the two USHORTS on line 12 might be larger than an unsigned short can hold, and assigning that product to Area can cause truncation. In this particular case, you can safely ignore this warning. |
|
|
|
|
|
|
|
|
|
On line 5, USHORT is typedef'd as a synonym for unsigned short int. The program is otherwise identical to Listing 3.2, and the output is the same. |
|
|
|
|
|
|
|
|
When to Use short and When to Use long |
|
|
|
|
|
|
|
|
One source of confusion for new C++ programmers is when to declare a variable to be type long and when to declare it to be type short. The rule, when understood, is fairly straightforward: If there is any chance that the value you'll want to put into your variable will be too big for its type, use a larger type. |
|
|
|
|
|
|
|
|
As seen in Table 3.1, unsigned short integers, assuming that they are two bytes, can hold a value only up to 65,535. Signed short integers can hold only half that. Although unsigned long integers 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 float or double, and then you lose some precision. Floats and doubles can hold extremely large numbers, but only the first 7 or 19 digits are significant on most computers. That means that the number is rounded off after that many digits. |
|
|
|
|
|
|
|
|
Wrapping Around in unsigned Integers |
|
|
|
|
|
|
|
|
The fact that unsigned long integers have a limit to the values they can hold is only rarely a problem, but what happens if you do run out of room? |
|
|
|
|
|