Skip to content
Codescope

References vs pointers

A pointer is a box holding an address. A reference is not a box at all.

intro8 min7 steps

Before you start

In C, if you want a function to modify a caller's variable, you pass a pointer. C++ adds a second option: a **reference**, written int&, which acts like the original variable itself.

The mental model: a pointer is a box that *holds an address*. A reference is not a box at all — it is another *name* for something that already exists.

This lesson shows the practical difference: references cannot be null, cannot be reassigned to point elsewhere, and read like normal variables. That trades pointer flexibility for pointer safety.

Stack

main()
xint
10
0x7ffd1a10

Step 1 of 7. One int, one box. `x` is 4 bytes at `0x7ffd1a10` holding 10. Nothing surprising yet — this is the same model as C. What follows are two different ways to reach these bytes from somewhere else.

01 / 07

Step 01 / 07

One int, one box

x is 4 bytes at 0x7ffd1a10 holding 10. Nothing surprising yet — this is the same model as C.

What follows are two different ways to reach these bytes from somewhere else.

references-vs-pointers.cppC++
#include <iostream>void addOne(int &r) { r += 1; }void addTwo(int *p) { *p += 2; }int main() {    int  x   = 10;    int &ref = x;    int *ptr = &x;    ref  = 42;    *ptr = 7;    addOne(x);    addTwo(&x);    return 0;}