A Reference is an alternative name (an alias) for an already existing variable. Once a reference is initialized to an object, either the original variable name or the reference name can be used to read or modify the data.
| Property | Reference (T&) |
Pointer (T*) |
|---|---|---|
| Initialization | Must be initialized at declaration | Can be uninitialized (wild pointer risk) |
| Nullability | Cannot be null (always points to an object) | Can be nullptr or NULL |
| Reassignment | Cannot be reseated to another variable | Can be freely reassigned to different addresses |
| Syntax | Clean, natural variable syntax (ref = 10) |
Requires explicit dereference (*ptr = 10) |
| Arithmetic | No pointer arithmetic supported | Supports arithmetic (ptr++, ptr + 4) |
#include <iostream>
void swapByRef(int& a, int& b) {
int temp = a;
a = b;
b = temp;
}
int main() {
int x = 10, y = 20;
std::cout << "Before swap: x=" << x << ", y=" << y << "\n";
swapByRef(x, y); // Clean call without messy & symbols!
std::cout << "After swap: x=" << x << ", y=" << y << "\n";
// Output: x=20, y=10
return 0;
}
Boost your C++ proficiency by studying these closely connected core modules:
Understanding memory addressing and nullability.
Understanding Rvalue references (&&) vs Lvalue references (&).
Pass by reference parameter conventions.