What is a reference variable in C++?

C++ProgrammingServer Side Programming

Reference variable is an alternate name of already existing variable. It cannot be changed to refer another variable and should be initialized at the time of declaration and cannot be NULL. The operator ‘&’ is used to declare reference variable.

The following is the syntax of reference variable.

datatype variable_name; // variable declaration
datatype& refer_var = variable_name; // reference variable

Here,

datatype − The datatype of variable like int, char, float etc.

variable_name − This is the name of variable given by user.

refer_var − The name of reference variable.

The following is an example of reference variable.

Example

 Live Demo

#include <iostream>
using namespace std;
int main() {
   int a = 8;
   int& b = a;
   cout << "The variable a : " << a;
   cout << "\nThe reference variable r : " << b;
   return 0;
}

Output

The variable a : 8
The reference variable r : 8

In the above program, a variable of integer type is declared and initialized with a value.

int a = 8;

The variable b is declared which is referring variable a.

int& b = a;
raja
Published on 08-Nov-2018 06:19:29
Advertisements