Introduction
Variables are names of memory locations. They are used to store data, to change their value, and to reuse the information. Variables represent memory locations through symbols so that they are easily identifiable. A variable that points to an object of a particular class, allowing you to access the value of an object, is called a reference variable. Have you ever thought about what happens when the reference variable points to an invalid location? Don't worry! Coding Ninjas has you covered. In this blog, we will discuss if a reference variable can point to an invalid location. Let's get started.
Also see, Literals in C.
What is a reference variable?
A reference variable is the alternate name of an already existing variable. It should be initialised at the time of declaration and cannot be null. The reference variable cannot be changed to refer to another variable. The operator '&' is used to declare the reference variable.
Syntax:
datatype variable_name;
datatype& reference_var = variable_name;
Here is an example of a reference variable.
#include <iostream>
using namespace std;
int main() {
int var1 = 2;
int& var2 = var1;
cout << "The first variable has value : " << var1;
cout << "\nThe reference variable has value : " << var2;
return 0;
}
Output:
The variable a: 8
The reference variable r: 8
You practice by yourself with the help of online c++ compiler.