Skip to content

Chapter 10 of 31

Pointers and References

Reason about addresses, nullability, aliasing, references, constness, and function pointers.

40 minutes 10 quick checksBy Subha Prasad
Lesson 10 of 31Course navigation

Lesson content

Read, practise, then check your understanding

A pointer stores an address and may be nullptr; dereferencing a null, dangling, or invalid pointer is undefined behavior. A reference is an alias that must bind at initialization and cannot be reseated. Neither form implies ownership by itself.

void increment(int& value) { ++value; }

int value{10};
int* pointer{&value};
if (pointer != nullptr) {
    *pointer += 2;
}
increment(value);

const int* points to a read-only integer, int* const is a fixed pointer to mutable integer, and const int* const fixes both. Keep constness close to the contract.

Arithmetic, arrays, and lifetime

Pointer arithmetic is defined only within an array object (including one-past-the-end) and advances in units of the pointed type. Prefer iterators or std::span because they carry stronger range meaning. A pointer or reference dangles when its object dies, moves in a way that invalidates it, or a container reallocates.

Pointers to functions

int add(int a, int b) { return a + b; }
using Operation = int (*)(int, int);
Operation operation{&add};
int result = operation(3, 4);

Function pointers enable callbacks but cannot hold captured lambdas. Templates avoid type erasure; std::function can hold diverse callables at some runtime cost. Use references for required objects, pointers for optional non-owning access, and values, containers, or smart pointers to express ownership.

Knowledge check

Answer every question correctly to complete this chapter.

What must a reference bind to when initialized?
Which pointer represents no object?
What does *pointer do?
When is a pointer preferable to a reference parameter?
What is a dangling reference?
Can a reference be reseated after initialization?
What does &value produce?
What does const T& support efficiently?
What is pointer arithmetic scaled by?
What should express ownership instead of a raw pointer?

0 of 10 checks passed

Your progress is saved on this device.