There are several reasons why reference variables are used in C++:
To pass variables by reference to functions: Reference variables can be used to pass variables by reference to functions, which allows the function to modify the original variable rather than a copy. This can be more efficient than passing variables by value, especially for large data structures.
To return multiple values from a function: Reference variables can be used to return multiple values from a function by using them as output parameters. For example:
void getValues(int &x, int &y)
{
x = 10;
y = 20;
}
In this example, the getValues function returns two values by modifying the reference variables x and y.
To improve code readability: Reference variables can make code easier to read by providing more descriptive names for variables. For example:
int x = 10;
int &y = x;
In this example, the reference variable y is an alias for the variable x, and it can be used in place of x throughout the code. This can make the code easier to understand by giving y a more descriptive name.
Overall, reference variables are an important concept in C++ programming, and they are used for a variety of purposes, including passing variables by reference to functions, returning multiple values from a function, and improving code readability.