C++

C++ References

C++ References

A reference variable is a special feature in C++. It is an alias i.e. another name assigned to an already existing variable. After you assign a reference to a variable, either the variable name or the reference name may be used to refer to the variable. It is created with the & operator. Its syntax is 

type variablename;
....
type &referencename = variablename;

For e.g.

string welcomeStr = "Welcome to Jio";  // Welcome string of an app
string &alias2WelcomeStr = welcomeStr;    // reference to Welcome string


References serve 4 prime purpose in C++. 

  1. You can change the passed parameters in a functio call. If a function receives a reference to a variable, it can modify the value of the variable and it will ger reflected in the parent function. For example, see the following code to swap the values of a and b. The swap function modifies a and b since they are passed as references
    Save the following code in a file say swap.cpp.
#include<iostream>
using namespace std;
  
void swap (int& a, int& b)
{
    int temp = a;
    a = b;
    b = temp;
}
  
int main()
{
    int a, b;
    cout<<"Enter a: ";
    cin>>a;
    cout<<"Enter b: ";
    cin>>b;
    cout << "Before swap, a: " << a << " and b: " << b<<endl;
    swap( a, b );
    cout << "After swap, a: " << a << " and b: " << b<<endl;
    return 0;
}

Now compile and run the code to see values of a and b change by calling swap() function.

(base) 23:30:59:~ % g++ swap.cpp
(base) 23:31:02:~ % ./a.out     
Enter a: 10
Enter b: 20
Before swap, a: 10 and b: 20
After swap, a: 20 and b: 10

2.Reference help us avoid making a copy of large structures: If we have to pass a large object as an argument to a function and that function will not be changing this object, then passing it in any way will cause a new copy to be created which waste memory, storage and cpu. By using references, we can avoid this wastage. See the following code snippet

struct StudentRecord 
{
   int rollNumber;
   string name;
   string Homeaddress;
   string AadharNumber;
   .....
};
  
// If we remove & in below function, a new
// copy of the student object is created. 
// We use const to avoid accidental updates
// in the function as the purpose of the function
// is to Display s only.
void Display(const Student &s)
{
    cout<<"Student record: "<<endl;
    cout << s.name << "  " << s.Homeaddress << "  " << s.rollNumber<<"  " << s.AadharNumber;
}

3. We can use references in a loop to modify all elements in one go. See the following code snippet and copy it in a file say referenceLoop.cpp

#include <bits/stdc++.h> 
using namespace std; 
  
int main() 
{ 
    vector<float> result{ 10.1, 20.2, 30.3, 40.4, 50.5 }; 
  
    // We can modify all elements in 
    // one go if we use reference
    for (float &x : result) 
        x = x + 5.05;
  
    // Print each element
    for (float x : result) 
       cout << x << " "; 
  
    cout<<endl;
    return 0; 
} 

Now compile and execute it. You will get all 5 elements of vector changed.

(base) 23:51:28:~ % g++ referenceLoop.cpp

(base) 23:55:06:~ % ./a.out 

15.15 25.25 35.35 45.45 55.55

4.We can use references in each loop to avoid creating a copy of individual objects. This is handy when objects are large.  

Most of the young programmers get confused  between references and pointers. There are 3 major differences between references and pointers. One, we have a NULL pointer but there is no NULL reference. A reference must always be associated with a previously declared variable. Second, reference is use once object i.e. once you assign a reference to an object, you cannot reassign it to another object. Pointers, on the other hand, can be changed to point to another object at any pint of time. Third, reference must be initialized at its creation time whereas pointers can be initialized at any time.