Back to slide -- Keyboard shortcut: 'u'  previous -- Keyboard shortcut: 'p'  next -- Keyboard shortcut: 'n'          references/ref-basic-2.cc - No operator operates on a reference as such.Lecture 2 - slide 15 : 29
Program 2

// Illustrate references vs. pointers.
// Example similar to the function g on page 98 in 'The C++ Programming Language' (3ed)
// and on page 190 in 'The C++ Programming Language' (4ed).
// The morale is that ++ applied on a pointer does pointer arithmetic. 
// ++ applied on a reference does not affect the reference as such.

#include <iostream>
#include <string>

using namespace std;

void g(){

  // HERE WE ILLUSTRATE REFERENCES:
  int ii = 0;
  int& rr = ii;              // rr is a reference to ii - an alias to ii
  rr++;                      // ii is incremented.
                             // The reference is NOT incremented itself.
  cout << ii << endl;        // 1
  cout << rr << endl;        // 1

  // HERE WE DO SIMILAR THINGS WITH POINTERS:
  int* pp = &rr;             // pp is really the address of ii (via rr) - a pointer to ii.
                             // NOT a pointer to a reference!
  (*pp)++;                   // ii is incremented again, 
  pp++;                      // The pointer as such is incremented - pointer arithmetic.
                             // Not good...
  cout << ii  << endl;       // 2
  cout << *pp << endl;       // 2673944
  pp--;                      // Better revert to the original value
  cout << *pp << endl;       // Still 2. No harm has been done. 

}

int main(){
  g();
}