Exercises in this lecture  previous -- Keyboard shortcut: 'p'        Go to the slide, where this exercise belongs -- Keyboard shortcut: 'u'  

Exercise 2.2
Pointers in combination with references


In this exercise we will explore pointers and references relative to each other. Play and learn! We do this in context of a function that returns the maximum of two doubles. Here is the function with call-by-value parameters:

  double max(double a, double b){
    return a < b ? b : a;
  }

In all cases below, program the max function, call it, make make sure you get the expected result from the call.

Please be aware that the cases become increasingly strange...

  1. Make a version with C-style call by reference parameters - pointers passed by value.
  2. Make a version with call by C++ references. Also, return a double&.
  3. Make a version with call by C++ const references instead of call by value parameters.
  4. Demonstrate that pointers to references do not exist.
  5. Make a version with references to pointers. Does that make sense to you?
  6. Next, make version with const references to pointers.
  7. Finally, a version with const references to pointers to double constants

Can you imagine other interesting variations?


Solution