Lesson 12 of 25

References

References vs Pointers

A reference is an alias for an existing variable. Unlike pointers, references cannot be null and cannot be reassigned after initialization.

Example
int original = 42;
int& ref = original;  // ref is an alias for original

cout << ref << endl;      // 42
ref = 100;
cout << original << endl;  // 100 (modified through reference)

// References in functions
void swap(int& a, int& b) {
    int temp = a;
    a = b;
    b = temp;
}

int x = 10, y = 20;
swap(x, y);
cout << x << " " << y << endl; // 20 10

// Const reference — read-only alias
const int& cref = original;
// cref = 50; // Error! Cannot modify through const reference