REFERENCE VARIABLE
C++ allows to create a reference to an existing variable. It provides a new name to an existing variable. Once a reference is created for a variable, either the variable name or reference name can be used to refer the variable.
The reference variable internally works as an constant pointer i.e. Once a reference is created for a variable, then it can't be changed. It is dereferenced internally without the use of dereferencing operator(*).
PROGRAM
// Program to illustrate reference variable
#include <iostream>
using namespace std;
int main()
{
int num;
cout<<"\nENTER A NUMBER: ";
cin>>num;
int &RefToNum = num;
// RefToNum is a reference variable referring to num
cout<<"\nVALUE OF NUM: "<<num;
cout<<"\nVALUE OF REFERENCE TO NUM: "<<RefToNum;
cout<<"\n\nSQUARING NUM...";
num = num*num;
cout<<"\n\nVALUE OF NUM: "<<num;
cout<<"\nVALUE OF REFERENCE TO NUM: "<<RefToNum;
/* Both variable results in the same value as
they are operating on the same memory location */
return 0;
}
OUTPUT
2 comments
commentsNice write up :)
ReplyAdd comments in your code too, in order to make it easier for people to understand.
Thanks :)
Thank you, the same is updated! Do provide your feedback here: https://goo.gl/forms/rXKC0EIeX9
Reply