What’s the value of a null pointer?
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.
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:
Sadly, this just adds confusion to our code:
In case you’re a C programmer who’s looked at this (and is feeling pretty smug at the moment):
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
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:
Can’t wait? Download the full set of articles as a PDF, here.
To learn more about Feabhas’ Modern C++ training courses, click here.
Latest posts by Glennan Carnie (see all)
- Technical debt - August 22, 2018
- Your handy cut-out-and-keep guide to std::forward and std::move - April 26, 2018
- Setting up Sublime Text to build your project - April 12, 2018