• Home
  • What is a reference variable in C++?

What is a reference variable in C++?

In C++, a reference variable is a variable that is an alias for another variable. A reference variable is declared using the & operator, and it is initialized with the address of another variable. For example:

int x = 10;
int &y = x; // y is a reference to x

In this example, the reference variable y is an alias for the variable x, and any changes made to y will also be reflected in x.

One of the main advantages of reference variables is that they 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.

Reference variables are also often used to return multiple values from a function. For example:

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

In this example, the swap function takes two reference variables as arguments and swaps their values.

Overall, reference variables are an important concept in C++ programming, and they are used to create aliases for variables and to pass variables by reference to functions.