Example 1 - Reference and Pointer arguments

//func_p_r.cc
#include <iostream>

void ref_int(int&);
void ptr_int(int*);

int main()
{ int x = 22;

  cout << x << endl;
  ref_int(x);  cout << x << endl;
  ptr_int(&x); cout << x << endl;
  
  return 0;
}

void ref_int(int& y)
{ for (int i = 0; i < 10; i++)
   y = y + i;
}

void ptr_int(int* y)
{ for (int i = 0; i < 10; i++)
   *y = *y - i;
}

In the case of the pass by reference since ref_int() expects a reference the compiler takes care of it for us and we can use the argument just like it was a "normal" variable.

ref_int(x);
...
void ref_int(int& y)
{ for (int i = 0; i < 10; i++)
   y = y + i;
}

In the case of passing a pointer we need to use the address-of operator - &x - and the function has to have a pointer argument. The function also has to dereference the pointer in order to access the value pointed to.

ptr_int(&x);
...
void ptr_int(int* y)
{ for (int i = 0; i < 10; i++)
   *y = *y - i;
}

In the bad old days all reference arguments were handled this way, addresses were explicitly passed as arguments. It works fine as long as the programmer remembers what is happening.


Return to lesson


Copyright © 1999 - 2001 David Beech