In C++, functions can be used to pass data by reference, allowing the function to modify the actual argument passed. This is in contrast to passing by value, where a copy of the argument is made.
When passing by reference, the function works with the original variable, so any changes made inside the function are reflected outside the function as well. This is achieved using reference parameters in the function definition.
To define a function with reference parameters, use the ampersand (&) after the data type in the parameter list. Here’s an example:
void swap(int &a, int &b) {
int temp = a;
a = b;
b = temp;
}
In this example, the swap function takes two reference parameters, a and b. When called, it swaps the values of the two variables passed to it.
To call a function with reference parameters, simply pass the variables as you would for a normal function:
int main() {
int x = 10;
int y = 20;
cout << "Before swap: x = " << x << ", y = " << y << endl;
swap(x, y);
cout << "After swap: x = " << x << ", y = " << y << endl;
return 0;
}
In this example, the main function calls swap with x and y. Before the call, x is 10 and y is 20. After the call, x is 20 and y is 10.
Reference parameters are similar to pointer parameters but have some key differences: