Pointers & References
The GPS and the Nickname
Imagine you live at 42 Elm Street. A pointer is like writing that address on a sticky note β it doesn't contain your house, it just tells someone where to find it. A reference is like a nickname β if your friends call you "Al" instead of "Alexander," they're still talking about the same person. No address needed, just another name.
In C++, these two ideas β pointers and references β are the foundation of working with memory directly. Let's dig in.
Raw Pointers: * and &
A pointer is a variable that stores a memory address. You declare one with * and get an address with &.
int* pβ "p is a pointer to an int"&xβ "the address of x"*pβ "the value at the address p holds" (dereferencing)
Think of & as asking "where do you live?" and * as "let me visit that address."
Pointer Basics
References: Another Name for the Same Thing
A reference is declared with & (yes, the same symbol β context matters). Once bound, a reference is the original variable. There's no separate address to manage, no dereferencing needed.
Reference Basics
Swap: Pointer Version vs. Reference Version
The classic swap function shows the difference beautifully. With pointers, you pass addresses and dereference. With references, the syntax is clean β the compiler handles the indirection for you.
Swap β Pointers vs. References
nullptr β Not NULL
In modern C++, use nullptr instead of NULL or 0. nullptr is type-safe β it's specifically a null pointer, while NULL is just the integer 0 wearing a disguise, which can cause ambiguity in function overloads.
nullptr Check
const Pointer vs. Pointer to const
This trips up everyone at first. Read the declaration right to left:
const int* pβ pointer to a const int (can't change the value, can change where it points)int* const pβ const pointer to an int (can change the value, can't change where it points)const int* const pβ const pointer to a const int (can't change anything)
const Pointer Variations
Pointer vs. Reference: When to Use Which
Here's the quick guide:
| Feature | Pointer | Reference |
|---|---|---|
| Can be null | Yes | No |
| Can be reassigned | Yes | No (bound at creation) |
| Syntax overhead | More (* and &) | Less (automatic) |
| Arithmetic | Yes (p++, p+3) | No |
Rule of thumb: Use references when you can, pointers when you must. You need pointers for optional values (nullable), dynamic memory, and data structures like linked lists.