C++ Pointers and References
Understand the address-of operator, pointers, dereferencing, references, and how to pass them to functions.
Fifth post in the basic C++ series. Variables live in memory at an address. Pointers and references are two ways to talk about a variable indirectly — both essential in C++.
Address of a variable#
Every variable sits at a memory address. Take it with &:
int a = 42;
std::cout << &a << '\n'; // something like 0x7ffee2b3d5accppPointers#
A pointer stores an address. It has a type that says what it points to:
int a = 42;
int* p = &a; // p points to acppDereference with * to read or write through the pointer:
std::cout << *p << '\n'; // 42
*p = 100; // changes a
std::cout << a << '\n'; // 100cppThe null pointer#
A pointer can hold no address. Use the keyword nullptr and always check before dereferencing:
int* p = nullptr;
if (p != nullptr) {
std::cout << *p << '\n';
}cppDereferencing nullptr is a crash — a null pointer dereference.
References#
A reference is an alias for an existing variable. It is bound once and can never be re-bound:
int a = 42;
int& r = a; // r is another name for a
r = 100; // changes a
std::cout << a << '\n'; // 100cppReferences cannot be null and cannot point to a different variable later.
Passing to functions#
Pass by reference to modify the caller’s variable without copying:
void increment(int& x) {
++x;
}
int main() {
int a = 5;
increment(a);
std::cout << a << '\n'; // 6
}cppUse const int& when you want to avoid copying but not modify:
void describe(const std::string& s) {
std::cout << s.size() << '\n';
}cppPointers vs references#
| Pointer | Reference | |
|---|---|---|
| Can be null | Yes (nullptr) | No |
| Can change target | Yes | No |
| Must dereference | Yes (*) | Implicitly |
| Reassignment | p = &other | Not allowed |
In modern C++, prefer references for function parameters. Use pointers when “no value” is a valid state or when rebinding is needed.
Conclusion#
Pointers and references both reach variables indirectly. Prefer references for safety, use pointers when null or rebinding matters. Next in this series: classes and objects.