Wednesday, 8 January 2014

What is reference variable in c++

 
Reference is used in c++ to create a alias for the variable. It is just used like a nick name. Consider you  have variable a, if you need to use the variable a as b, you can create a reference.
To create a reference append a ampersand symbol as prefix to variable at a time of creation. Don’t confuse with the ampersand symbol. It is not a symbol used for address reference here.
Consider the example

int a=5;
int a2=10;
int &b=a;
int &c; //Not valid need to initialize
int &d=NULL;  //not valid statement
int *p=NULL;
int e=p;  //not valid assigning NULL pointer
b=a2;  //not valid cannot initialize reference variable again

In above example, the alias name for a is created, it is b.
So here are some scenarios

cout<<a;  //prints 5
cout<<b;  //prints 5
b++;  //changes the value of a
cout<<a; //prints 6
cout<<b;  //prints 6

Datatype conflict:
You cannot make a reference for the different data types  For Eg you cannot refer a integer variable to the double reference.

int a;
int &b=a;  /valid assignment
double &c=a;   //invalid assignment

pointer vs references:

The pointer and reference are almost same with some of the following differences.
1.      You can assign a NULL value to pointer, but you cannot do that in reference.
2.      Pointer can be reassigned many number of times, but in a reference we cannot do that. Reference can be initialized only once.
3.      Reference must be initialized at the time of declaration.  But pointers can be initialized any number of time.
4.      If pointer is incremented it will point to next memory address, whereas if reference is incremented the variable that reference is pointing to will be incremented.

Although, reference seems to be different concept, Probably it is internally treated as a pointers by the compiler.  Some other compilers will treat it as alias.