C++ how to use reference variables

www.ig‮editfi‬a.com

In C++, reference variables are created using the & symbol. When declaring a reference variable, the & symbol is placed after the data type, followed by the name of the variable. For example:

int x = 5;
int& ref = x;

Here, ref is a reference to x. Any changes made to ref will also affect x, and vice versa.

Reference variables are commonly used to pass arguments to functions by reference, which allows the function to modify the original value of the argument. Here's an example:

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

int main() {
    int x = 5;
    increment(x);
    cout << x;  // Output: 6
    return 0;
}

In this example, the increment() function takes a reference to an integer as its argument. When the function increments the value of num, it actually modifies the original value of x in main().