Bitesize Modern C++: nullptr

What’s the value of a null pointer?

  • 0
  • NULL
  • NUL

No doubt you’ve been involved in the (always heated) discussions about which is the correct one (By the way, if you said NUL you need to take yourself to one side and give yourself a stern talking to).

The arguments tend to go something like this:

  • 0 is the only ‘well-known’ value a pointer can be set to that can be checked.
  • NULL is more explicit than just writing zero (even though it is just a macro definition wrapper)

The problem with using 0 or NULL is that they are, in fact, integers and that can lead to unexpected behaviours when function overloading occurs.

image

Based on what we’ve just discussed it should be pretty straightforward to see that the int overload will be called. (This rather weakens the argument that NULL is more explicit – explicitly confusing in this case!)

It gets worse: Implementations are free to define NULL as any integer type they like. In a 32-bit system it might seem reasonable to set NULL to the same size as a pointer:

image

Sadly, this just adds confusion to our code:

image

In case you’re a C programmer who’s looked at this (and is feeling pretty smug at the moment):

image

Unfortunately this won’t compile, because a void* cannot be implicitly converted to an int, long or int* (or any other type) in C++.

In C++11 the answer to the question of the value of a pointer is much more simple: it is always nullptr

In our code, using nullptr instead of NULL gives the results we expect

image

nullptr is a keyword that represents any ‘empty’ pointer (and also any pointer-like objects; for example smart pointers) A nullptr is not an integer type, or implicitly convertible to one (it’s actually of type nullptr_t).  However, it is implicitly convertable to bool; and to maintain backward compatibility the following code will work as expected:

image

More information

Can’t wait? Download the full set of articles as a PDF, here.

To learn more about Feabhas’ Modern C++ training courses, click here.

Glennan Carnie

Glennan Carnie

Technical Consultant at Feabhas Ltd
Glennan is an embedded systems and software engineer with over 20 years experience, mostly in high-integrity systems for the defence and aerospace industry.

He specialises in C++, UML, software modelling, Systems Engineering and process development.
Glennan Carnie

Latest posts by Glennan Carnie (see all)

Dislike (0)

About Glennan Carnie

Glennan is an embedded systems and software engineer with over 20 years experience, mostly in high-integrity systems for the defence and aerospace industry. He specialises in C++, UML, software modelling, Systems Engineering and process development.
This entry was posted in C/C++ Programming and tagged , , , , , . Bookmark the permalink.

Leave a Reply