Skip to main content

Reference variable with example

Short answer

A reference variable is an alias for an existing variable, declared with & and must be initialized. It shares the same memory address and cannot be rebound. Example: int x=10; int &r=x; r+=5; changes x to 15. Used for call by reference and avoiding copies.

Explain the concept of reference variable with suitable example.

A reference variable is an alias (another name) for an existing variable. It is declared with & and must be initialised when declared. After that, any operation on the reference works directly on the original variable.

Syntax

data_type &ref_name = variable_name;

Example

#include <iostream>
using namespace std;

int main()
{
    int x = 10;
    int &r = x;        // r is another name of x
    r = r + 5;         // changes x
    cout << x << " " << r << endl;       // 15 15
    cout << &x << " " << &r << endl;     // same address
    return 0;
}

Properties

  • Must be initialised at declaration; int &r; is an error.
  • Cannot be re-bound to another variable after initialisation.
  • It has the same address as the variable; it does not take a separate copy.
  • No null reference exists.

Uses

  1. Call by reference: the function changes the caller's variables without using pointers.
void swap(int &a, int &b)
{
    int t = a; a = b; b = t;
}
// swap(x, y) exchanges x and y in main
  1. Avoids copying large objects (const T &).
  2. Return by reference allows a function call on the left of =.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Object Oriented Programming chapter 3 questions →