C++ ยท Chapter 24 of 49

C++ References

A reference is an alias for an existing variable, declared with `&`, and once bound it cannot be reseated to refer to another variable. Modifying a reference modifies the original variable directly.

References are widely used as function parameters to avoid copying large objects and to allow a function to modify the caller's variable.

Declaring a reference

`int& ref = x;` makes ref another name for x. Any change to ref changes x, and vice versa, since they share the same memory location.

References in function parameters

`void increment(int& n) { n++; }` modifies the caller's variable directly, avoiding a copy and enabling 'pass by reference'.

Example 1 (cpp)
int x = 5;
int& ref = x;
ref = 10;
std::cout << x;
Output
10

Changing ref changes x since they refer to the same memory.

Example 2 (cpp)
void addOne(int& n) { n++; }
int main() {
    int x = 5;
    addOne(x);
    std::cout << x;
}
Output
6

Passing by reference lets the function modify the original variable.

Key points

  • A reference is an alias, declared with &.
  • References cannot be null or reseated after binding.
  • Pass-by-reference avoids copying and allows mutation.
  • const int& is used to pass efficiently without allowing changes.
๐Ÿ’ก Note: Use `const T&` as a function parameter when you want efficiency but don't want the function to modify the argument.

๐Ÿ“ Quick Quiz

1. What symbol declares a reference?

2. Can a reference be reseated to refer to a different variable?

3. Passing by reference is mainly used to: