Reference in C++

A reference is a synonym for another variable. The value of the variable changes, if the value of variable or value of reference changes. Here is an example of reference.

#include<bits/stdc++.h>
using namespace std;
int main(){
	int n = 50;
	int& pn = n;
	cout<<"n = "<<n<<" pn = "<<pn<<endl;
	n = n+10;
	cout<<"n = "<<n<<" pn = "<<pn<<endl;
	pn = pn*2;
	cout<<"n = "<<n<<" pn = "<<pn<<endl;
	return 0;
}

As the value of n changes, the value of rn changes. And as the value of rn changes, the value of n changes.

output of the above program. reference
output of the above program. reference

Leave a Reply