What are References and how it is different from pointers?

Learn: The difference between references [preferably used in C++] and pointers [preferably used in C/C++] and would ultimately help in answering a C++ interview question.
Submitted by Deepak Dutt Mishra, on April 30, 2018

This article consists of the description of both references [in C++] and pointers [preferred in C/C++]. The description would finally lead to a conclusion which will draw a difference line between pointers and reference. This article does not conclude that one of these should not be preferred. It will just simply provide you some basic overview over the topics.

References in C++

A reference variable is basically nothing but an alias name or in simpler terms another name declared for a pre-existing variable. For the purpose of declaring a reference or an alias the address-of (&) is used. This operator placed before the variable in declaration statement. After a reference is declared then that variable can be called by either using the original variable name or the alias name given to that variable using & operator.

In simpler words, let a variable name say int a=10; be a variable declared. This variable is a label marking a memory location. Similarly, when we declared a reference say int &r=a; this is yet another label marking that same memory location so we can access that memory by calling any of these two variable names.

References are similar to pointers or in simpler way of understanding they are weak pointers basically developed for the purpose of is in functions as they act as formal parameters[variables declared inside the function declaration parenthesis] in various functions to support reference passing in functions. When a reference is passed into a function, the function works on the original copy of the variable instead of duplicate values as in value passing functions. This enables us to show the operations performed inside the function in the outside of the function. Also references are used for function arguments and return values.

There are two basic concepts which a C++ programmer should have knowledge on the topic of references:

a) References as Parameters

This is how a call by reference function works using references.

Example:

#include <iostream>usingnamespacestd;/* Here &a,&b are references which are used as formal paramater*/voidswap(int&a,int&b){int t;
t=a;
a=b;
b=t;}intmain(){//Here x,y are local variablesint x=100;int y=200;cout<<"Initial value of x:"<<x<<endl;cout<<"Initial value of y:"<<y<<endl;//Calling the function swapswap(x,y);cout<<"Value of x after swapping:"<<x<<endl;cout<<"Value of y after swapping:"<<y<<endl;return0;}

Output

Initial value of x:100
Initial value of y:200
Value of x after swapping:200
Value of y after swapping:100