Lesson 5 | Call-by-reference |
Objective | Examine C++'s implementation of call-by-reference |
C++ Call by Reference
The chief use of reference declarations is in formal parameter lists. This allows C++ to have call-by-reference arguments directly, a feature not available in C.
Example
Let uslook at an example program that uses reference declarations and call-by-reference.
The function greater
exchanges two values if the first is greater than the second.
int greater(int& a, int& b){
if (a > b) { //exchange
int temp = a;
a = b;
b = temp;
return (1);
}
else
return (0);
}
If i
and j
are two int
variables, then
greater(i, j)
uses the reference to i
and the reference to j
to exchange, if necessary, their two values. In traditional C, this operation must be accomplished using pointers and dereferencing.
Call-by-reference and const
When function arguments are to remain unmodified, it can be efficient and correct to pass them const
call-by-reference. This is the case for types that are structures.
struct large_size{
int mem[N];
//...other stuff
};
void print(const large_size& s){
//since s will not be modified
//avoid call-by-value copying
//...
}