Home C++ Tutorial Reference variable in C++

Reference variable in C++

by Anup Maurya
30 minutes read

In this tutorial, we learn about Reference Variables, you may already aware of normal variable and pointer variable.

What is Reference Variable?

C++ references allow you to create a second name for the a variable that you can use to read or modify the original data stored in that variable. A variable can be declared as a reference by putting ‘&’ in the declaration. 

A reference variable must be initialized at the time of declaration.

#include <iostream>
using namespace std;
 
int main()
{
    int m = 20;
    int &ref = m;  // ref is a reference to m.
    ref = 20;   // Value of m is now changed to 20
    cout << "m = " << m << '\n';
    m = 40;   // Value of m is now changed to 40
    cout << "ref = " << ref << '\n';
    return 0;
}

Output

m = 20
ref = 40

When we declare a reference and assign it a variable, it will allow us to treat the reference exactly as though it were the original variable for the purpose of accessing and modifying the value of the original variable even if the second name (the reference) is located within a different scope. This means, for instance, that if you make your function arguments references, and you will effectively have a way to change the original data passed into the function.

Let understand with an example,

#include <iostream>
using namespace std;

void swap(int& first, int& second)
{
	int temp = first;
	first = second;
	second = temp;
}

int main()
{
	int a = 2, b = 3;
	cout<<"Before Swapping:"<<endl;
	cout<<"a:"<<a<<" b:"<< b<<endl;
	swap(a, b);
	cout<<"After Swapping:"<<endl;
	cout<<"a:"<<a<<" b:"<< b;
	return 0;
}

Output

Before Swapping:
a:2 b:3
After Swapping:
a:3 b:2

What’s the difference between the reference and the pointer in C++?

A pointer in C++ is a variable that holds the memory address of another variable. A reference is an alias for an already existing variable. Once a reference is initialized to a variable, it cannot be changed to refer to another variable. Hence, a reference is similar to a const pointer.

related posts

Leave a Comment

Enable Notifications OK No thanks