Sams Teach Yourself C++ in 21 Days

(singke) #1
result = 56 + 32 // result = 88
result = 12 – 10 // result = 2
result = 21 / 7 // result = 3
result = 12 * 4 // result = 48

Subtraction Troubles
Subtraction with unsignedintegers can lead to surprising results if the result is a nega-
tive number. You saw something much like this yesterday, when variable overflow was
described. Listing 4.2 shows what happens when you subtract a large unsigned number
from a small unsigned number.

LISTING4.2 A Demonstration of Subtraction and Integer Overflow
1: // Listing 4.2 - demonstrates subtraction and
2: // integer overflow
3: #include <iostream>
4:
5: int main()
6: {
7: using std::cout;
8: using std::endl;
9:
10: unsigned int difference;
11: unsigned int bigNumber = 100;
12: unsigned int smallNumber = 50;
13:
14: difference = bigNumber - smallNumber;
15: cout << “Difference is: “ << difference;
16:
17: difference = smallNumber - bigNumber;
18: cout << “\nNow difference is: “ << difference <<endl;
19: return 0;
20: }

Difference is: 50
Now difference is: 4294967246
The subtraction operator is invoked for the first time on line 14, and the result is
printed on line 15, much as you might expect. The subtraction operator is called
again on line 17, but this time a large unsigned number is subtracted from a small
unsigned number. The result would be negative, but because it is evaluated (and printed)
as an unsigned number, the result is an overflow, as described yesterday. This topic is
reviewed in detail in Appendix C, “Operator Precedence.”

OUTPUT


72 Day 4


ANALYSIS
Free download pdf