on Leave a Comment

C++ reference variables

C++ introduces some new concepts that were not previously available in C language. One of the concept is reference variable. A reference variable is used to store the reference of an ordinary variable.

Syntax of Reference Variable:

data-type &reference-name=variable-name

Example:

int a=10;
int &b=a;

Here a is int type variable, and b is reference variable storing the reference of variable a. Reference variable b is another name of variable a.

The statements 

cout<<a;
cout<<b;

both will print 10.

The statement

a=a+10;

will change the value of both a and b. 

The statement

b=b+10;

will change the value of both a and b.

Here, & is not an address of operator. The int & means reference to int.

Following examples are legal:

int a[5];
int &b=a[5];
int x;
int *y=&x;
int &z=*y;
int &p=10;
char &c='\n';

An application of reference variables is in passing arguments to functions

int add(int &x,int &y);
int main()
{
    int a=10;
    int b=20;
    int c;
    c=add(a,b);
    cout<<"Sum is "<<c;
}
int add(int &x,int &y)
{
    return x+y;
}

Here, we are passing references of a and b to x and y. Then, sum of x and y is assigned to c.

Important points about reference variable

Reference variable must be initialized during declaration.

Reference variable can be initialized with already declared variable.

Declaration of reference variable is always preceded with ‘&’ symbol (Here it is not address of operator).

Reference variable cannot be updated till the end of program.

Reference variable can only store the reference of variable of same data type. Example, float type reference variable can only store the reference of float type variable. 

0 comments:

Post a Comment