Reference Variables:

             C++ Programming introduces a new kind of variable known as reference variable. A reference variable provides an alias (Alternative name) of the variable that is previously defined. For example, if we make the variable sum a reference to the variable total, the sum and total can be used interchangeably to represent that variable.
 Syntax for defining reference variable
Data_type & reference_name = variable_nane
 

Example:
int total=100 ;
int &sum=total;


              Here total is int variable already declared. Sum is the alias for variable total. Both the variable refer to the same data 100 in the memory.


 cout< <total;  

and 

cout<<sum; gives the same output 100.
 And total= total+100;
 Cout< <sum;    //gives output 200

                

A reference variable must be initialized at the time of declaration. This establishes the correspondence between the reference and the data object which it means. The initialization of reference variable is completely different from assignment to it. A major application of the reference variables is in passing arguments to function.
 

//An example of reference

#include<iostream.h>
#include<conio.h>
 void main()
{
int x=5;
int &y=x;     //y is alias of x     

cout< <"x="< <x< <"and y="< <y< <endl;
 y++;     //y is reference of x;
cout< <"x="< <x< <"and y="< <y< <endl;
 getch();

}

Share To:

Arogya Thapa Magar

Post A Comment:

0 comments so far,add yours