Home What are the differences between a pointer variable and a reference variable in C++?
Reply: 0

What are the differences between a pointer variable and a reference variable in C++?

user11221 Published in September 19, 2018, 3:21 am

I know references are syntactic sugar, so code is easier to read and write.

But what are the differences?

Summary from answers and links below:

  1. A pointer can be re-assigned any number of times while a reference cannot be re-assigned after binding.
  2. Pointers can point nowhere (NULL), whereas a reference always refers to an object.
  3. You can't take the address of a reference like you can with pointers.
  4. There's no "reference arithmetic" (but you can take the address of an object pointed by a reference and do pointer arithmetic on it as in &obj + 5).

To clarify a misconception:

The C++ standard is very careful to avoid dictating how a compiler may implement references, but every C++ compiler implements references as pointers. That is, a declaration such as:

int &ri = i;

if it's not optimized away entirely, allocates the same amount of storage as a pointer, and places the address of i into that storage.

So, a pointer and a reference both use the same amount of memory.

As a general rule,

  • Use references in function parameters and return types to provide useful and self-documenting interfaces.
  • Use pointers for implementing algorithms and data structures.

Interesting read:

  • My all-time favorite C++ FAQ lite.
  • References vs. Pointers.
  • An Introduction to References.
  • References and const.
share|improve this question
  • 70
    I think point 2 should be "A pointer is allowed to be NULL but a reference is not. Only malformed code can create a NULL reference and its behavior is undefined." – Mark Ransom Oct 8 '10 at 17:21
  • 11
    Pointers are just another type of object, and like any object in C++, they can be a variable. References on the other hand are never objects, only variables. – Kerrek SB Jun 16 '12 at 10:14
  • 10
    This compiles without warnings: int &x = *(int*)0; on gcc. Reference can indeed point to NULL. – Calmarius Aug 13 '12 at 9:00
  • 8
    reference is a variable alias – Khaled.K Dec 23 '13 at 8:53
  • 13
    I like how the very first sentence is a total fallacy. References have their own semantics. – Lightness Races in Orbit Jun 1 '14 at 1:58

33 Answers 33

active oldest votes
1 2 next
up vote 99 down vote
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.60373 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO