c-plus-plus
  1. c-plus-plus-what-is-a-reference-variable

What is a Reference Variable in C++?

In C++, a reference variable is an alias for an existing variable. It allows you to refer to the same memory location as the original variable. When you modify the value of a reference variable, you are actually modifying the value of the original variable.

Syntax

int var = 10;
int& ref_var = var;

The & symbol is used to declare a reference variable. It is important to note that a reference variable must be initialized when it is declared, and it cannot be reassigned to another variable.

Example

#include <iostream>
using namespace std;

int main() {
    int original_var = 10;
    int& ref_var = original_var;
    
    cout << "Original Value: " << original_var << endl;
    cout << "Reference Value: " << ref_var << endl;
    
    ref_var = 20;
    
    cout << "Original Value After Reference Update: " << original_var << endl;
    cout << "Reference Value After Reference Update: " << ref_var << endl;
    
    return 0;
}

Output

Original Value: 10
Reference Value: 10
Original Value After Reference Update: 20
Reference Value After Reference Update: 20

Explanation

In the above example, we have created a variable named original_var and assigned it a value of 10. We then create a reference variable named ref_var and initialize it to original_var. This creates an alias for the original_var. We then print the value of both variables to verify that they are the same.

We then update the value of the ref_var to 20. This actually updates the value of original_var as well, since ref_var is just an alias for original_var. We then print the value of original_var and ref_var to see the updated values.

Use

Reference variables are often used as a way to pass arguments to functions without making a copy of the original variable. This can save memory and improve performance in some cases. They can also be used to create aliases for variables that are used elsewhere in the code.

Important Points

  • A reference variable is an alias for an existing variable.
  • A reference variable must be initialized with an existing variable.
  • A reference variable cannot be reassigned to another variable.
  • Modifying the value of a reference variable also modifies the value of the original variable.

Summary

In summary, a reference variable in C++ is an alias for an existing variable. It can be used to create aliases for variables used elsewhere in the code or to pass arguments to functions without making a copy of the original variable. It is important to note that a reference variable must be initialized and cannot be reassigned to another variable.

Published on: