C++ Program to illustrate reference variable [DEVCPP/GCC]


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

C++ Program to illustrate reference variable with output

C++ Program to illustrate reference variable


Share this

Related Posts

2 comments

comments
November 5, 2016 at 2:41 PM delete

Nice write up :)

Add comments in your code too, in order to make it easier for people to understand.

Thanks :)

Reply
avatar
November 6, 2016 at 8:34 PM delete

Thank you, the same is updated! Do provide your feedback here: https://goo.gl/forms/rXKC0EIeX9

Reply
avatar

FIND US ON FACEBOOK!