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 pointers - C-style 'call-by-reference'
double max0_ptrs(double* a, double* b){
  return *a < *b ? *b : *a;
}

// By pointers - C++ style references
double& max0_refs(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. Pointers to references do not make sense.
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 << max0(a, b) << endl;         // Call by value

  cout << max0_ptrs(c, d) << endl;    // Call by C-style references - pointers by value

  cout << max0_refs(a, b) << endl;    // Call by C++ -style references. Returns a Lvalue reference. 
                                      // The assignment max0_refs(a, b) = 3;  will change the value of b.

  cout << max1(a, b) << endl;         // Call by C++ const reference

  cout << max3(c, d) << endl;         // Call by C++ reference to pointers

  cout << max4(&a, &b) << endl;

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

  cout << max4(&e, &f) << endl;     // ERROR: Invalid conversion from 'const double*' to 'double*'

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