Reference Variable in C++ language

C++ language introduce a new kinds of variable which is used as a reference for another variable in a same program is known as a reference variable. It is used as a alternative name for another variable in the same program. For example, if we make a variable sum as a reference variable for another variable total which is further used to add two different number taken as input in the program. 

Here, sum and total both are used interchangeably to represent variable in a single program. The syntax for creating reference variable is:

Syntax for creating Reference Variable.

data_type & reference_name = Variable_name;

Example for reference variable:

int y = 100;
int &x = y;

Here, y is a variable of integer type having value 100 which is already declared. Now, x is used as a reference variable for y. 
Both the variable y and x, now having value 100 and these variable used interchangeably with each other.  
In both cases the output is printed as given below:
cout<<x; // here the value of x is printed 100.
cout<<y; // here the value of y is printed 100.


Note: if we change value of any variables during the program, then it automatically change the value of another variable.
Suppose, during the program we change y = y +300, then it automatically change the value of x to 400 and if we make a change in x then it automatically change the value of y also.



Thanks
Mukesh Rajput
Mukesh Rajput

Mukesh Rajput

I am a Computer Engineer, a small amount of the programming tips as it’s my hobby, I love to travel and meet people so little about travel, a fashion lover and love to eat food, I am investing a good time to keep the body fit so little about fitness also..

Post A Comment:

0 comments: