In C++, call-by-reference is implemented using references. References are essentially aliases for existing variables, allowing functions to directly access and modify the original variable's value without creating a copy.
Here's how it works:
-
Declaration: When declaring a function parameter as a reference, an ampersand (
&
) is placed after the type. For example:
void myFunction(int& num);
-
Function Call: When calling the function, you pass the variable directly:
int x = 10;
myFunction(x); // x is passed by reference
-
Internal Implementation: The compiler typically implements references using pointers. Behind the scenes, the reference parameter acts as a pointer to the original variable's memory location. Any changes made to the reference parameter within the function directly affect the original variable.
Key Advantages of Call-by-Reference:
- Efficiency: Avoids the overhead of copying large objects or data structures.
- Modification: Allows functions to modify the original variable's value.
- Multiple Return Values: Enables functions to effectively return multiple values by modifying variables passed by reference.
Example:
#include <iostream>
void swap(int& a, int& b) {
int temp = a;
a = b;
b = temp;
}
int main() {
int x = 5, y = 10;
std::cout << "Before swap: x = " << x << ", y = " << y << std::endl;
swap(x, y);
std::cout << "After swap: x = " << x << ", y = " << y << std::endl;
return 0;
}
In this example, the `swap` function takes two integer references as parameters. By modifying the references `a` and `b`, the function directly swaps the values of the original variables `x` and `y`.
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.