C++ Reference Variables in functions

https:‮www//‬.theitroad.com

In C++, reference variables can also be used as function parameters. When a function is called with a reference parameter, the reference parameter is an alias for the argument that was passed to the function. This means that any changes made to the reference parameter inside the function will also affect the original argument that was passed to the function.

Here is an example of how to use reference variables in functions:

#include <iostream>
using namespace std;

void swap(int &x, int &y) {
    int temp = x;
    x = y;
    y = temp;
}

int main() {
    int a = 5, b = 10;
    cout << "Before swap: a = " << a << ", b = " << b << endl;
    swap(a, b);
    cout << "After swap: a = " << a << ", b = " << b << endl;
    return 0;
}

In this example, we define a function swap that takes two integer reference parameters x and y. Inside the function, we swap the values of x and y. Then, in the main function, we call swap with a and b as arguments. Because a and b are passed as reference parameters, the values of a and b are swapped inside the swap function. After the function call, the values of a and b have been swapped in the main function as well.

Output:

Before swap: a = 5, b = 10
After swap: a = 10, b = 5