New in C++ is the ability to pass-by-reference. Unfortunately, to denote this, the designers of C++ chose to overload another symbol which is already in use: the ampersand (&). If a variable name in a parameter list of a function is immediately preceeded by an &, then the body of the function will reference the actual passed parameter instead of making a copy. Inside the function, we simply refer to the parameter name and use it as if the & was not there. The only difference is that the original argument is changed as well. Program 1 shows how this works.
Program 1. Passing by value.
#include <iostream> using namespace std; void f( int & n ) { cout << "Inside f( int & ), the value of the parameter is " << n << endl; n += 37; // we just refer to the paramter 'n' cout << "Inside f( int & ), the modified parameter is now " << n << endl; return; } int main() { int m = 612; cout << "The integer m = " << m << endl; cout << "Calling f( m )..." << endl; f( m ); cout << "The integer m = " << m << endl; return 0; } |
1. Try this with other types: double and char.
2. Write a function void abs( int & n ) which sets the integer pointed to by the argument to its absolute value.
3. Given the function in Question 2, call abs( 0 ). What will happen?
4. Comment on the wisdom of a function like
int m = -5; abs( m ); cout << "The value of m = " << m << endl;
modifying m without a visible assignment.
5. Write a function which takes references to two ints and swaps them if the first is greater than the second. (hint)