Skip to content


November 3, 2011

C++11 adds a null pointer constant called nullptr. The use of nullptr should be preferred over 0 or NULL. GCC just added a warning for the use of 0 as a pointer, so they are strongly encouraging you to use nullptr. I will dig into the standard further down, and you will see that there is very good reason for this. But first, all the normal ways of using it.

Suppose that you had a function f which was overloaded to take both int and char*. In C++03, If you wanted to call it with a null pointer, and you used the value 0, then you would call the one overloaded for int.

void f(int);
void f(char*);

void g() 
  f(0); //calls f(int)

This is probably not what you wanted. C++11 solves this with nullptr.

Now you can write the following:

void g()
  f(nullptr); //calls f(char*)

Basically nullptr is a pointer type—it can only be converted to other pointer types, not any integer type. Technically nullptr has type std::nullptr_t. The type is declared in <cstddef> as:

namespace std
  typedef decltype(nullptr) nullptr_t;

There are some oddities about pointers when it comes to comparisons and conversions. For the operators <= and >=, two values of type std::nullptr_t shall compare as true. Comparing with < or > gives false. Comparing anything else with a value of type std::nullptr_t is unspecified. Comparing anything using != or == with nullptr gives true or false if it is not null or null respectively.

Essentially what this means is that an implementation is free to use whatever value they like for nullptr. I’m sure that in practice, every implementation in the world will use zero, but technically all that the standard requires is that there be some null value. This means that you should most definitely not use 0 in your code anymore, all null pointer constants should be specified using nullptr.


From → Language

  1. JoshG permalink

    Does this affect the use of the following construct?

    Object* pObject = GetObject(“name”)
    if (!pObject)

    // Do something on pObject

    • No, this works the same.

      From 4.12.1 in the standard:

      A zero value, null pointer value, or null member pointer value is converted to false;
      any other value is converted to true.

      So however it is implemented, if pObject == nullptr, !pObject will convert it to false.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: