BlogsDope image BlogsDope

References in C++

Feb. 28, 2021 C C++ FUNCTION 1683

A variable is called a reference variable if it can become an alternative name for an existing variable. For example let's suppose my name is "Priyansh" and my friends from school know me with this name and i am registered in my school with this name. But my friends near my house call me with my nickname "Sonu". Now every time someone gives money to Priyansh, it is equivalent to giving money to Sonu. Ultimately there are two names of a single person.

So, if Priyansh is a variable name, then Sonu is another name for an already existing variable Priyansh. Simply, a reference variable is an alias. So, we can access the variable with both the names.

A variable can be declared as a reference by putting ‘&’ in the declaration.

Let's declare it and see : 
int student_roll = 14;

We can declare reference variables for student_roll as follows :
int& my_roll = student_roll;

We read it "my_roll" is an integer reference initialized to student_roll".

//C++ code
#include <iostream>
using namespace std;
int main()
{
	int student_roll=10;
	int& my_roll=student_roll;	// reference variable my_roll created for student_roll

	cout<< "Value of student_roll before :"<< student_roll << endl;
	cout<< "Value of my_roll before :"<< my_roll << endl;

	my_roll=my_roll+5;//adding 5 to the reference variable

	cout<<"After adding 5 to  my_roll number \n";

	cout<< "Value of student_roll now :"<< student_roll << endl;
	cout<< "Value of my_roll now :"<< my_roll << endl;

	return 0;
}

Output : Value of student_roll before : 10
         Value of my_roll before : 10
         After adding 5 to my_roll number 
         Value of student_roll now : 15
         Value of my_roll now : 15

Well, there are more things we should know about reference variable and they are that we should declare and initialize references at single step.

int a = 10;
int& b = a;
//this is the correct way. 

But you can't do this :
int& b;
​ b = a;

With the above name example, we can also conclude that a reference cannot be reassigned, we can't refer to two things with one variable at one time.
int a = 10;
int b = 5;
int& ref1 = a;
int& ref1 = b;

This is not allowed, as multiple declaration is not allowed.

Now, let's look at some of the applications of it.

Examples of reference

1. Reference Variable as a function parameter

This is also known as call by reference. If a function receives a reference to a variable, it can modify it's value. So, that eliminates the copying of parameters. Hence, it permits the manipulation of parameters in function call.

Consider the example:

//C++ code
#include <iostream>
using namespace std;
int callByReference(int& a) // call by reference
{
    a = a + 1;
	return a;
}

int main()
{
	int age = 18,ans;
	ans = callByReference(age);
	cout<<"Value of age now is : "<<ans<<endl;
	return 0;
}

Output : Value of age now is : 19

Call by reference can also be helpful in swapping values of variables.

2. Modification in for-each loop

We can modify elements from an array, list, etc using a reference variable inside for each loop using a reference variable.

Consider the example : 

//C++ code
#include<iostream>
using namespace std;
int main()
{
    int arr[5] = {2,4,6,8,10};

    for (int &temp : arr) // temp is the reference variable
        temp = temp + 1;  //so, changes made will modify the array.

    for(int i=0;i<5;i++)
        cout<<arr[i]<< " "; 

    return 0;
}

Output : 3 5 7 9 11

We can also use references in for each loop to avoid a copy of individual objects when objects are large.
Now let's discuss about something very important, and a must-know discussion.

Pointers v/s References

Well, a pointer in C++ is a variable that holds the memory address of another variable. But a reference is an alias for an already present variable. These are some difference between pointers and references:

  1. We can point at different things/objects but we can refer to one thing at a time. Once a reference is initialized to a variable, it cannot be changed to refer to a variable object. But pointer can be changed to point to any variable of the same type.
  2. We can point at something, also we can not point at anything literally Null. Well yes, a pointer can be assigned to a NULL value. But references cannot be NULL.
  3. A pointer needs to be dereferenced with a *, but references can be simply used by their names.
  4.  A reference must be initialized when declared. There is no such restriction with pointers.
     And due to the above limitations, references in C++ cannot be used for implementing data structures like Trees, linked lists etc. 
  5. A pointer has its own memory address and size but a reference variable shares the same address with the variable it is referring to, but it takes some space is allocated on stack for it. But you will never be able to get this address from you code because you are not required to know the address.
  6. Pointer variables has different levels of indirection like single pointer, double pointer and more, whereas reference variable has only single level.
    So, int &ref = a; //this is valid.
    But int &&b = ref; //this is not valid (reference to reference) and an error will occur.
  7. You can perform arithmetic operations on pointers whereas there is nothing called Reference arithmetic.

Conclusion: References are more or less same thing like pointers but are little safer and cleaner to use. Reality is that references are internally implemented using pointers. So, we would recommend to use both when they're most helpful like use reference variable for function calls when modifying the original inputs, for passing large sized arguments. Use references where you can instead of pointers.


Liked the post?
Hi, I am Priyansh Jha. I am a pre-final year student of Electronics and Communication major undergraduate.
Editor's Picks
0 COMMENT

Please login to view or add comment(s).