C++ for Embedded · Interview question

When should you use a pointer instead of a reference?

A strong answer

When you need a capability a reference can't provide. First, optionality: if "no object" is a valid state, an optional callback, a maybe-present device, a pointer can be nullptr while a reference can't represent absence. Second, reseating: a variable that refers to different objects over time, like a cursor walking a linked list or a "current buffer" that changes. Third, address arithmetic and hardware: iterating with pointer arithmetic, or accessing a fixed memory-mapped register like *(volatile uint32_t*)0x40000000, you can't make a reference to a raw numeric address or do arithmetic on a reference. So the decision rule is: default to references for "definitely-present object I won't reseat," and use a pointer precisely when you need null, reseating, or arithmetic.

What a weak answer sounds like

You know the answer. Do you know what gets you dinged?

Pro breaks down the answer most candidates actually give to this question — and the specific reason an interviewer marks it down. It’s the difference between sounding correct and sounding senior, on all 472 questions.

From the lesson

References vs Pointers

References are aliases that can't be null and can't be reseated. When to reach for a reference, when you still need a pointer, and why const& is the default way to pass objects.

More References vs Pointers questions

Browse all 472 interview questions
When should you use a pointer instead of a reference? | EmbeddedPrep.io