skip to content

In C++, why should you write nullptr instead of NULL or 0 for a null pointer?

level: juniorimportance: must knowfreq 72%

answer

  1. a type of its own
  2. std::nullptr_t converts only to pointers
  3. overloads on int and int*
  4. NULL is implementation-defined

basics

~20 s

nullptr has its own type, std::nullptr_t, which converts implicitly to every pointer type but never to an integer. NULL and 0 are integer null pointer constants, so overload resolution and template deduction can treat them as numbers.

solid answer

~40 s

`nullptr` (C++11) is a prvalue of type `std::nullptr_t`; it converts to any object pointer, function pointer or pointer-to-member, and to `bool` only by direct initialization, but never implicitly to `int`. `0` is an integer literal that *also* happens to be a null pointer constant, and the standard leaves `NULL` as an implementation-defined null pointer constant - `0`, `0L`, or a compiler builtin such as Clang's `__null`. So with overloads `report(int)` and `report(int*)`, `report(0)` silently picks the `int` overload and `report(NULL)` is ambiguous on Clang with libc++, while `report(nullptr)` picks the pointer. Templates make it worse: once `0` is deduced as `int` it stops being a null pointer constant at all. `nullptr` states intent and survives both; `-Wzero-as-null-pointer-constant` flags the old spellings.

code

cpp · 11 lines
cpp
#include <cstddef>
#include <iostream>

void report(int value)  { std::cout << "report(int) " << value << '\n'; }
void report(int* entry) { std::cout << "report(int*) " << (entry ? "set" : "null") << '\n'; }

int main() {
    report(0);        // report(int): 0 is an int before it is a null pointer
    report(nullptr);  // report(int*): std::nullptr_t converts only to pointers
    // report(NULL);  // Apple clang + libc++: error, call to 'report' is ambiguous
}

go deeper

for a junior

Recall that nullptr has the type std::nullptr_t, converts only to pointer types, and that 0 and NULL are integers that merely act as null pointer constants.

for a middle

Walk through overload resolution for f(int) versus f(int*) with 0, NULL and nullptr, and say why NULL's result depends on the implementation.

for a senior

Explain why a null pointer constant is a property of an expression, so forwarding 0 through a template or factory loses it, and name the warning that enforces nullptr.

for a principal

Treat the migration as a mechanical modernization with clang-tidy plus a warning gate, keeping NULL only in headers that a C compiler must also read.

## Three spellings of null C++ has three common ways to write "this pointer points at nothing", and only one of them is a pointer in its own right: | Spelling | Type of the expression | Standard status | |---|---|---| | `0` | `int` | an integer literal with value zero, which is also a **null pointer constant** | | `NULL` | implementation-defined | a macro that expands to an implementation-defined null pointer constant | | `nullptr` | `std::nullptr_t` | a keyword (C++11) whose prvalue is a null pointer constant of a dedicated type | The draft's own footnote on `NULL` says possible definitions include `0` and `0L` but **not** `(void*)0` - unlike C, C++ has no implicit conversion from `void*` to other object pointers, so that C definition would be useless. Clang with libc++ on this machine expands `NULL` to the builtin `__null`, and `auto a = NULL;` deduces `long` there. Code that depends on which integer `NULL` really is cannot be portable. ## What overload resolution does with each Overload resolution ranks conversions; the null spellings rank very differently: - `report(0)` with overloads `report(int)` and `report(int*)`: `0` to `int` is an **exact match**, `0` to `int*` is a pointer conversion, so the `int` overload wins - silently, with no warning. - `report(NULL)`: on Clang with libc++, `__null` has an integer type, so both overloads need a conversion of the same rank and the call is rejected as `call to 'report' is ambiguous`. On another implementation where `NULL` is plain `0`, the same line silently calls `report(int)` instead. The same source line means different things on different toolchains. - `report(nullptr)`: `std::nullptr_t` has no implicit conversion to `int` at all, so the only viable candidate is `report(int*)`. This is the scenario interviewers like: a legacy API gains an overload that takes an integer handle, and every caller that passed `0` or `NULL` "for no layer" quietly starts calling the wrong function. ## Templates lose the null-ness of 0 A null pointer constant is a property of an **expression**, not of a type. The literal `0` qualifies; a variable of type `int` that holds zero does not. Forwarding through a template therefore breaks it: ```cpp template <class Fn, class Arg> void call_later(Fn fn, Arg arg) { fn(arg); } call_later(open_layer, 0); // Arg = int -> error: cannot initialize int* with an int call_later(open_layer, nullptr); // Arg = std::nullptr_t -> converts to int* ``` Factories, `std::make_unique`, `emplace_back` and thread constructors all forward their arguments this way, so `nullptr` is the only spelling that reliably arrives as a null pointer. ## Facts about std::nullptr_t worth knowing 1. It is declared in `<cstddef>` as `using nullptr_t = decltype(nullptr);`. 2. Its `sizeof` and alignment are those of `void*`, yet its value representation can comprise no bits. 3. It converts to every pointer and pointer-to-member type, so one `nullptr` works for `int*`, `void (*)()` and `int Widget::*` alike. 4. You can overload on it - `void reset(std::nullptr_t)` - to give "clear" a distinct overload. ## Legacy spellings and their replacements Most codebases that predate C++11 carry the same handful of patterns, and each has a direct replacement: 1. `if (p == NULL)` or `if (p == 0)` becomes `if (p == nullptr)` or simply `if (p)` / `if (!p)`. 2. `return 0;` from a function returning `Layer*` becomes `return nullptr;` - the integer spelling hides that the function returns a pointer. 3. Default arguments such as `Layer* parent = 0` become `Layer* parent = nullptr`, so a later overload on an integer cannot capture the default. 4. Sentinel arguments to variadic C functions, such as the terminating null of `execl`, must arrive as a pointer: a `NULL` that expands to plain `0` is passed as an `int`. A `nullptr` argument is converted to `void*` when it passes through the ellipsis, and `static_cast<char*>(nullptr)` matches the `char*` the function documents exactly. ## The team rule and the tools - Write `nullptr` for every null pointer in C++ code; keep `NULL` only in headers shared with C. - Compare with `p == nullptr` or test `if (p)`; both are fine, but never compare against `0`. - Turn on `-Wzero-as-null-pointer-constant` (Clang and GCC both document it): Clang reports `zero as null pointer constant` and even suggests the `nullptr` fix-it. - `clang-tidy`'s `modernize-use-nullptr` rewrites a legacy codebase mechanically. The point to make in an interview is not style: `nullptr` is the only null spelling whose **type** says "pointer", which is what overload resolution and template deduction actually look at.

  • Why can't C++ define NULL as (void*)0 the way many C headers do?
    C converts `void*` implicitly to any object pointer type, so `(void*)0` works there. C++ removed that implicit conversion for type safety, so `int* p = (void*)0;` would not compile. The standard therefore requires `NULL` to be an integer-like null pointer constant, and its footnote names `0` and `0L` as possible definitions while ruling out `(void*)0`.
  • If NULL already works in most code, what concrete bug does migrating to nullptr prevent?
    Overload hijacking and broken forwarding. When someone adds `f(int)` beside `f(T*)`, every `f(0)` caller silently switches overloads, and `f(NULL)` either switches or stops compiling depending on the toolchain. Arguments forwarded through templates such as `make_unique` or `emplace_back` lose null-ness once deduced as an integer. `nullptr` has type `std::nullptr_t`, so it can only ever select a pointer parameter.

  • NULL is defined as (void*)0 in C++ just like in C
  • nullptr is just a macro for 0 added for readability
  • nullptr implicitly converts to int when an int overload is the only candidate
  • f(NULL) always calls the pointer overload
  • Passing 0 through a template still gives a null pointer