Pointers come from plain C, and references were added by C++. They
have both similarities and differences which can be terribly confusing.
This page is supposed to point out some of these, in the faint hope
that it will make some sense.
- Difference: Pointers are declared using a *, references using a & in
- Similarity: Both allow one variable to refer to another, so that operating on
a pointer or reference expression can change another variable.
- Difference: Any operation on a reference is applied to what it refers to. It is
implicitly de-referenced. Operations on a pointer variable change
the pointer variable, unless the * operator is used.
must be explicitly de-referenced.
- Put that another way: for reference r,
r = something
assigns something to the variable r refers to.
For pointer p, p = something
assigns p, probably making it point to a different place.
To change the variable that p
points to, say *p = something.
- Difference: References refer to something when they are created, and cannot
refer to a different variable during their lifetime. Pointers
may refer to different things at different times, or to nothing.
- Consequence: You may have a null pointer. There is no such thing as a
- Difference: The & used in a declaration declares a reference. The &
used in an expression creates a pointer value which can be assigned to
a pointer variable or passed to a pointer parameter. (The
perpetrator of this arrangement is still at large.)
- Similarity: Both can be used to allow a function to change a variable in the
- Difference: When a parameter of type reference to T is passed an argument
of type T, the reference is automatically created. To pass
an argument of type T to a parameter of pointer to T,
a pointer value must be sent. This can be done using a &
in the argument expression.
- Consequence: When using a reference parameter, you generally see a
by the parameter, and nothing by the argument. When passing to a
pointer, you see a * by the parameter and a & by the
argument (unless it is an array).
- Difference: Arrays and pointers have a special relationship, but references work with
with arrays exactly as they do with other types.
Pointers are the more general facility. Anything you can do with a
reference, you could re-write to do with a pointer. Some pointer jobs
cannot be done with a reference.
If something can be written using either pointers or references, both
versions will likely produce essentially
the same machine code. The source code differences are
artifacts of the language design and semantics.