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.
int *p = nullptr; if (p == nullptr) { /* ... */ }
Try it
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.
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
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
nullptralways gives the right representation. - Variadic functions: pass
nullptr, not0orNULL, as a terminating pointer. A plain0is anint, and reading it asconst char *is undefined. - Dereferencing a null pointer is undefined behavior.
nullptronly makes the null value explicit. - Comparisons. A pointer can be compared with
nullptrby==and!=;if (!p)still works. - Same as
NULLfor ordinary code. There is no need to rewrite working code, but usenullptrin new C23 programs. - Pre-C23 compilers do not know the keyword. Use
NULLwhen you need C11/C17 compatibility. _Genericandtypeofcan tellnullptr_tapart fromvoid *, whichNULLcould not reliably do.- Memory functions such as
free(nullptr)andrealloc(nullptr, n)are well-defined.