< previous page page_47 next page >

Page 47
The semantics of prefix is this: increment the value and then fetch it. The semantics of postfix is different: fetch the value and then increment the original.
This can be confusing at first, but if x is an integer whose value is 5 and you write
int a = ++x;
you have told the compiler to increment x (making it 6) and then fetch that value and assign it to a. Thus a is now 6 and x is now 6.
If, after doing this, you write:
int b = x++;
you have now told the compiler to fetch the value in x (6) and assign it to b, and then go back and increment x. Thus, b is now 6 but x is now 7. Listing 4.2 shows the use and implications of both types.
LISTING 4.2 DEMONSTRATES PREFIX AND POSTFIX OPERATORS

d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
1:   // Listing 4.2 - demonstrates use of
2:   // prefix and postfix increment and
3:   // decrement operators
4:   #include <iostream.h>
5:   int main()
6:   {
7:       int myAge = 39;      // initialize two integers
8:       int yourAge = 39;
9:       cout << I am:\t << myAge << \tyears old.\n;
10:      cout << You are:\t << yourAge << \tyears old\n;
11:      myAge++;         // postfix increment
12:      ++yourAge;       // prefix increment
13:      cout << One year passes\n;
14:      cout << I am:\t << myAge << \tyears old.\n;
15:      cout << You are:\t << yourAge << \tyears old\n;
16:      cout << Another year passes\n;
17:      cout << I am:\t << myAge++ << \tyears old.\n;
18:      cout << You are:\t << ++yourAge << \tyears old\n;
19:      cout << Let's print it again.\n;
20:      cout << I am:\t << myAge << \tyears old.\n;
21:      cout << You are:\t << yourAge << \tyears old\n;
22:      return 0;
23: }

Output:
I am     39 years old
You are   39 years old
One year passes
I am     40 years old
You are   40 years old

 
< previous page page_47 next page >

If you like this book, buy it!