00 // Illustrate references vs. pointers.
01 // Example similar to the function g on page 98 in 'The C++ Programming Language' (3ed)
02 // and on page 190 in 'The C++ Programming Language' (4ed).
03 // The morale is that ++ applied on a pointer does pointer arithmetic. 
04 // ++ applied on a reference does not affect the reference as such.
05 
06 #include <iostream>
07 #include <string>
08 
09 void g()
10 {
11   using namespace std;
12 
13   // HERE WE ILLUSTRATE REFERENCES:
14   int ii = 0;
15   int& rr = ii;              // rr is a reference to ii - an alias to ii
16   rr++;                      // ii is incremented.
17                              // The reference is NOT incremented itself.
18   cout << ii << endl;        // 1
19   cout << rr << endl;        // 1
20 
21   // HERE WE DO SIMILAR THINGS WITH POINTERS:
22   int* pp = &rr;             // pp is really the address of ii (via rr) - a pointer to ii.
23                              // NOT a pointer to a reference!
24   (*pp)++;                   // ii is incremented again, 
25   pp++;                      // The pointer as such is incremented - pointer arithmetic.
26                              // Not good...
27   cout << ii  << endl;       // 2
28   cout << *pp << endl;       // 2673944
29   pp--;                      // Better revert to the original value
30   cout << *pp << endl;       // Still 2. No harm has been done. 
31 
32 }
33 
34 int main()
35 {
36   g();
37 }
38