Skip to content
Tutorials Center
My learning

Topics

C Reference ยท Keywords and Statements

The nullptr constant

Reference for C23 nullptr and nullptr_t: a typed null pointer constant, how it differs from NULL and 0, variadic calls and conversions.

nullptr is the C23 keyword for the null pointer constant. Its type is nullptr_t (declared in <stddef.h>), a type that converts to any pointer type and always yields a null pointer value. It converts to bool as false and compares equal to any null pointer.

Before C23, null pointers were written as NULL, which expands to 0, ((void *)0) or similar. Those forms are ambiguous in some contexts, especially variadic functions, where an integer 0 is not guaranteed to be passed like a pointer. nullptr removes the ambiguity because it has a pointer-like type.

C
int *p = nullptr;
if (p == nullptr) { /* ... */ }

Try it

C Using nullptr

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

C nullptr in a variadic call

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Syntax

C
nullptr
nullptr_t        /* declared in <stddef.h> */
Name Description
nullptr Constant of type nullptr_t. Never an integer constant.
nullptr_t Type of nullptr. Same size and representation as void *.
NULL Macro from <stddef.h>; its definition (integer 0 or (void *)0, or in C23 possibly nullptr) is implementation-defined.

Returns: a null pointer value of any pointer type it is converted to.

Errors: nullptr cannot be converted to an integer type, apart from bool, without a cast; int n = nullptr; is an error. It cannot be used as an arithmetic operand.

Usage notes

  • Null pointers do not have to be all-zero bits on exotic platforms, but converting nullptr always gives the right representation.
  • Variadic functions: pass nullptr, not 0 or NULL, as a terminating pointer. A plain 0 is an int, and reading it as const char * is undefined.
  • Dereferencing a null pointer is undefined behavior. nullptr only makes the null value explicit.
  • Comparisons. A pointer can be compared with nullptr by == and !=; if (!p) still works.
  • Same as NULL for ordinary code. There is no need to rewrite working code, but use nullptr in new C23 programs.
  • Pre-C23 compilers do not know the keyword. Use NULL when you need C11/C17 compatibility.
  • _Generic and typeof can tell nullptr_t apart from void *, which NULL could not reliably do.
  • Memory functions such as free(nullptr) and realloc(nullptr, n) are well-defined.