References in C++

References in C++ are very important as they can help you significantly reduce the running time of your code. A reference is simply another name to the same data value.

For example, here x_ref is a integer reference to x :

 int x = 10;  
 int & x_ref = x;  // reference initialization
 cout<<x_ref; // x_ref and x are same, i.e. 10  
 x_ref = 20;  
 cout<<x; // x is now 20  

A reference is declared by using the & sign [the & sign is also used to get memory location of a variable]. 

It is necessary to initialize a reference at the time it is declared. It is because you cannot have NULL references, so you need to initialize an explicit value to which declared reference is a reference to.  When you modify a reference, the original value also changes.

Another example,

 string s = "Hello, this is original string";  
 string &x = s;  
 x = "Modified string";  
 cout<<x; // outputs Modified string  
 cout<<s; // outputs Modified string  

A reference cannot be changed to refer to another variable. It can only refer to one value in its lifetime. Except, when using in for(auto &x : v) format, where v may be an array.


We know that a variable is a memory location, so a reference is also a variable with the same memory location. That is, the variable and reference both are the same value but provide different names through which we can access that location.


To pass a reference to a function, declare it in the function declaration : 

 void myfunction( int & ref1, int & ref2 ) { ref1 = ref2; }  
 void main()  
 {  
    int x = 10;  
    int y = 20;  
    myfunction(x, y);  
    cout<<x; // x is 20  
    cout<<y; // y is 20  
 }  

To return reference from a function, again declare it in the function declaration:
 int x = 10;  
 int & myfunction( ) { return x; }  
 void main()  
 {  
    int y = myfunction();  
    cout<<y; // y is 10  
 }  

You cannot return a reference to a local variable, as it will go out of scope. To do so, you must declare that variable as static.

Comments

Popular posts from this blog

In Place Algorithms