Significance of a reference variable.

Q7. What is the significance of a reference variable? Explain with example.

Ans. A reference is an alternative name for an object. A reference variable provides an alias for a previously defined variable. A reference declaration consists of a base type, an & (ampersand), a reference variable name equated to a variable name. The general form of declaring a reference variable is

type & ref-var = var-name;

where type is any valid C++ data type, ref-var is the name of reference variable that will point to variable denoted by var-name.

For example, if sum is declared as a reference variable for a variable total, then both sum and total represent the same variable and can be used interchangeably. Following program segment illustrates it:

int total;

int &sum = total;

total = 100;

cout,,”Sum = “<<sum<<”\n”;

cout<<”Total = “<<total<<”\n”;

 

The output of above program segment will be as follows:

Sum = 100

Total = 100

 

Both the variables refer to the same data object in the memory, thus, print the same value.

 

Leave a Reply

Your email address will not be published. Required fields are marked *

105 Views
%d bloggers like this: