Write a C++ program to demonstrate the use of returning a reference variable.

As the name states, reference variable is a variable that refers to the address of another variable. It is like giving a variable an alias or alternate name.

Tutorial 📺

Code 💻

#include<iostream.h>
#include<conio.h>

int& addNumbers(int &n1,int &n2)
{
  int sum = n1+n2;
  int &s = sum;
  return s;
}

void main()
{
  int a = 10, b = 20;
  clrscr();
  int &num1 = a, &num2 = b;
  cout << "Sum is :  " << addNumbers(num1,num2) << endl;
  getch();
}

In above code, we have defined a function called addNumbers() which accepts two arguments (references) of integer data type and also returns a reference variable of integer type.

In the main() function, we declared two variables: a and b. Next, we also declared two reference variables &num1 and &num2 which refer to variables a and b.

Finally, we are calling the addNumbers() function along with passing the reference variables num1 and num2, and ultimately displaying the value of returned reference variable.

Categorized in: