C++ Call by Reference
The call by reference method of passing arguments to a function copies the reference of an argument into the formal parameter. Inside the function, the reference is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument.
When passing values by reference, the reference of the parameter is passed to the function, just like passing other values. Consequently, in the following swap() function, you need to declare the function parameters as reference types, which is used to swap the values of two integer variables pointed to by the parameters.
// Function definition
void swap(int &x, int &y)
{
int temp;
temp = x; /* Save the value at address x */
x = y; /* Put y into x */
y = temp; /* Put x into y */
return;
}
Now, let's call the swap() function by passing values by reference:
Example
#include <iostream>
using namespace std;
// Function declaration
void swap(int &x, int &y);
int main ()
{
// Local variable declaration
int a = 100;
int b = 200;
cout << "Before swap, value of a :" << a << endl;
cout << "Before swap, value of b :" << b << endl;
/* Call the function to swap values */
swap(a, b);
cout << "After swap, value of a :" << a << endl;
cout << "After swap, value of b :" << b << endl;
return 0;
}
// Function definition
void swap(int &x, int &y)
{
int temp;
temp = x; /* Save the value at address x */
x = y; /* Put y into x */
y = temp; /* Put x into y */
return;
}
When the above code is compiled and executed, it produces the following result:
Before swap, value of a : 100
Before swap, value of b : 200
After swap, value of a : 200
After swap, value of b : 100