liveBook · Manning

Null pointer constant

As explained in Modern C, Third Edition

A pre-C23 null pointer constant is a compile-time constant expression of integer type and value zero or an expression of type void* that can be converted to a null pointer.

Consider `double const*const nix = nullptr; double const*const nax = nix;`. Both objects hold null pointer values, but neither object is a null pointer constant. Here, *constant* means a compile-time expression, not an object qualified with `const`. section 11.1.5

double const*const nix = nullptr;
double const*const nax = nix;

The two declarations separate a null pointer value from the expression used to initialize it. section 11.1.5

Before C23, a null pointer constant could be an integer constant expression with value zero, such as `0` or `0L`, or a qualifying `void*` expression such as `(void*)0`. An ordinary `void*` pointer object holding a null value does not thereby become a null pointer constant; nor does casting an arbitrary integer expression to `void*` make one. section 11.1.5 section 18.2

`NULL` must expand to a null pointer constant, but its type is not prescribed: implementations may use an integer zero or `(void*)0`. TAKEAWAY: Prefer `nullptr` to `NULL`; the latter’s expansion can matter in contexts such as variadic function calls. section 11.1.5

Testing the distinction

For an expression `X` that is either a null pointer constant or a `void*` pointer, consider `true ? (struct toto*)0 : (X)`. Its type is `struct toto*` when `X` is a null pointer constant, but `void*` when `X` is a `void*` pointer that is not one. This difference can be used in a compile-time test without evaluating `X`. section 18.2

true ? (struct toto*)0 : (X)

The conditional expression provides the type distinction used by the compile-time test. section 18.2

How Modern C, Third Edition covers it

How deep it goes
Defines the pre-C23 forms, examines permissible `NULL` expansions, and sketches a conditional-expression test without providing its completed macro.
Examples
Uses two `const` pointer objects, possible `NULL` expansions, and a conditional expression whose type distinguishes qualifying expressions.
What it assumes
Assumes familiarity with pointer declarations and expressions while defining the distinction between compile-time constants and `const`-qualified objects.
What you can do after
Evaluate/understand whether a pre-C23 expression qualifies as a null pointer constant and why `NULL` may hide a type choice.
How it connects
Connects null pointers to integer constant expressions, `void*`, conditional expressions, generic selection, and variadic functions.

Also explained in

Compare how 2 books explain null pointer constant →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C, Third Edition. The section links point to the parts of the book it draws on.