C++ Passing References as Parameters
We have discussed how to use pointers to implement call-by-reference functions. The following example uses references to implement call-by-reference functions.
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