C++ how to use reference variables in function

www.igi‮itf‬dea.com

In C++, reference variables can be used in functions to pass arguments by reference. This allows the function to modify the value of the original variable that was passed in, rather than just working with a copy of the value.

To use a reference variable in a function, you can declare the function parameter as a reference type using the "&" symbol. For example:

void increment(int& x) {
    x++;
}

int main() {
    int a = 5;
    increment(a);
    cout << a; // prints 6
    return 0;
}

In this example, the increment function takes an int& parameter, which means it expects an integer reference. When the function is called with a as the argument, a is passed as a reference to the function. Inside the function, the value of x is incremented, which also changes the value of a outside the function. When the value of a is printed in main, it shows the incremented value of 6.

Note that reference variables must be initialized when they are declared, and cannot be changed to refer to a different variable later on. Also, passing a variable by reference can be more efficient than passing it by value, especially for large objects.