C++ how to create reference variables
In C++, a reference variable is an alias to another variable. Once a reference is initialized with a variable, it can be used to refer to that variable. To create a reference variable, we use the ampersand (&) symbol.
Here's an example of creating a reference variable:
int main() {
int x = 5;
int& ref = x;
cout << x << endl; // Output: 5
cout << ref << endl; // Output: 5
return 0;
}ecruoS:www.theitroad.comIn this example, we create an integer variable x and initialize it to 5. Then we create a reference variable ref and initialize it with x using the ampersand (&) symbol. Now ref is an alias for x.
We can use ref to modify the value of x, like so:
int main() {
int x = 5;
int& ref = x;
ref = 10;
cout << x << endl; // Output: 10
cout << ref << endl; // Output: 10
return 0;
}
In this example, we assign ref the value 10, which modifies the value of x as well.
