Exercises in this lecture   Go to the notes, in which this exercise belongs -- Keyboard shortcut: 'u'   Alphabetic index   Course home   

Exercise solution:
Pointers in combination with references


Here are my variations of the max function:

#include <iostream>
#include <string>

// By value
double max0(double a, double b){
  return a < b ? b : a;
}

// By const reference
const double& max1(const double& a, const double& b){
  return a < b ? b : a;
}

// Pointers to references - does not compile.
const double& max2(double& *a, double & *b){ 
   return *a < *b ? *b : *a;
}

// References to pointers
double max3(double* &a, double* &b){     
  return *a < *b ? *b : *a;
}

// Const references to pointers
const double& max4(double* const &a, double* const &b){    
  return *a < *b ? *b : *a;
}

// const reference to const double pointer  (it is the doule which is constant).
const double& max5(const double* const &a,const double* const &b){     
  return *a < *b ? *b : *a;
}

int main(){
  using namespace std;

  double a = 1, b = 2;
  double *c = &a, *d = &b;
  const double e = 3, f = 4;

  cout << max1(a,b) << endl;

  cout << max3(c,d) << endl;

  cout << max4(&a,&b) << endl;
  cout << max4(c,d) << endl;
//cout << max4(&e,&f) << endl;     // ERROR

  cout << max5(&e,&f) << endl; 
}