What is a reference variable?
A reference is defined as an alias for another variable. In short, it is like giving a different
name to a pre-existing variable. Once a reference is initialized to the variable, we can use
either the reference name or the variable to refer to that variable.
Creating references in C++
y
The basic syntax to create a reference is -
Data type& new variable = previous variable
u d
S t
The newly created variable will now refer to the previous variable.
For example -
D
J M
int i = 17 // The variable i is declared as 17
Creating the reference of i will be as -
int& x = i // Here x will be called as the integer variable initialised to r
C++ code
#include <iostream>
using namespace std;
int main () {
int i; // Declare variable I as int
double d; // Declare variable d as double type
MCA/ [Link]/ [Link]/ BCA Internship/ Industrial/ Live Project Training.
Project Training in Python, Android, PHP, [Link], Machine Learning, SQL, JAVA,
Web Designing, Digital Marketing, SEO, SMO, C, C++. Call: 9649141215, [Link]
// declare reference variables for I and d
int& r = i;// r is reference to i
double& s = d;// s is reference to d
i = 5;
cout << "Value of i : " << i << endl;
cout << "Value of i reference : " << r << endl;
d y
d = 11.7;
tu
S
cout << "Value of d : " << d << endl;
cout << "Value of d reference : " << s << endl;
D
M
return 0;
J
Difference between Reference and Pointers
References Pointers
We cannot have a NULL reference. The concept of NULL pointers is allowed.
A reference assigned to a particular object Pointers, on the other hand, can point to different
cant be changed. objects at any time.
A reference is also initialized at the time of Pointers can be initialized at any time.
its creation.
JMD Study Computer Classes
Training > Project > Placement
MCA/ [Link]/ [Link]/ BCA Internship/ Industrial/ Live Project Training.
Project Training in Python, Android, PHP, [Link], Machine Learning, SQL, JAVA,
Web Designing, Digital Marketing, SEO, SMO, C, C++. Call: 9649141215, [Link]