Sams Teach Yourself C++ in 21 Days

(singke) #1
8:
9: int myAge = 39; // initialize two integers
10: int yourAge = 39;
11: cout << “I am: “ << myAge << “ years old.\n”;
12: cout << “You are: “ << yourAge << “ years old\n”;
13: myAge++; // postfix increment
14: ++yourAge; // prefix increment
15: cout << “One year passes...\n”;
16: cout << “I am: “ << myAge << “ years old.\n”;
17: cout << “You are: “ << yourAge << “ years old\n”;
18: cout << “Another year passes\n”;
19: cout << “I am: “ << myAge++ << “ years old.\n”;
20: cout << “You are: “ << ++yourAge << “ years old\n”;
21: cout << “Let’s print it again.\n”;
22: cout << “I am: “ << myAge << “ years old.\n”;
23: cout << “You are: “ << yourAge << “ years old\n”;
24: return 0;
25: }

I am 39 years old
You are 39 years old
One year passes
I am 40 years old
You are 40 years old
Another year passes
I am 40 years old
You are 41 years old
Let’s print it again
I am 41 years old
You are 41 years old
On lines 9 and 10, two integer variables are declared, and each is initialized with
the value 39. Their values are printed on lines 11 and 12.
On line 13,myAgeis incremented using the postfix increment operator, and on line 14,
yourAgeis incremented using the prefix increment operator. The results are printed on
lines 16 and 17, and they are identical (both 40 ).
On line 19,myAgeis incremented as part of the printing statement, using the postfix
increment operator. Because it is postfix, the increment happens after the printing, and so
the value 40 is printed again, and then the myAgevariable is incremented. In contrast, on
line 20,yourAgeis incremented using the prefix increment operator. Thus, it is incre-
mented before being printed, and the value displays as 41.
Finally, on lines 22 and 23, the values are printed again. Because the increment statement
has completed, the value in myAgeis now 41 , as is the value in yourAge.

OUTPUT


76 Day 4


LISTING4.3 continued

ANALYSIS
Free download pdf