C++ References

What is a Reference?

A reference is an alias for another variable. It refers to the same memory location.

int original = 100;
int& ref = original;

ref = 200;
cout << original;  // 200

Both variables refer to the same value in memory. So if one changes the other changes as well

Syntax

Use the ampersand & after the type to declare a reference:

int a = 5;
int& alias = a;

References in Functions

You can pass references to functions to avoid copying:

void modify(int& x) {
    x = 99;
}

int n = 10;
modify(n);
cout << n;  // 99

Why Use References?

  • To modify arguments inside functions
  • To avoid expensive copies of large objects
  • To return multiple values from functions (via multiple references)

Reference vs Pointer

Unlike pointers, references cannot be reassigned to another variable once set.

int a = 5, b = 10;
int* p = &a;    // pointer can be reassigned
p = &b;

int& r = a;
// r = b; ← modifies a, does not rebind the reference

const References

Use const to prevent modification:

void print(const int& value) {
    cout << value;
}

Commonly used for read-only access to large data like strings or vectors.

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic