Course contentsShow
← C
Lesson 970 of 1,21913. Advanced CFree lesson

C23: The `nullptr` constant

C23: The nullptr constant

What you'll learn: How to use the new type-safe nullptr keyword to avoid the ambiguities of the traditional NULL macro.

The Problem with NULL

For decades, C programmers used the NULL macro to represent a pointer that does not point to a valid memory location. However, NULL is an implementation-defined null pointer constant. Depending on your compiler, it might expand to the integer 0, a cast like ((void*)0), or (in C23) nullptr.

This unpredictable type causes subtle bugs in modern C. Standard C does not have function overloading, but it does rely on C11 _Generic selections and variadic functions (such as printf). If a compiler defines NULL as the plain integer 0, passing NULL to a variadic function that expects a pointer can be disastrous. The compiler might pass a 32-bit int instead of a 64-bit pointer, causing the function to read misaligned or garbage memory. Similarly, in a _Generic macro, NULL might unexpectedly match the int case rather than a pointer case.

Enter nullptr

The C23 standard resolves this by introducing nullptr. It is a built-in keyword, meaning you do not need to include any headers to use it.

The nullptr constant has its own unique, dedicated type called nullptr_t. (Note: While nullptr requires no headers, you must #include <stddef.h> if you want to declare a variable using the nullptr_t type itself). Unlike NULL, nullptr is guaranteed not to be an integer type. It will explicitly match nullptr_t in a _Generic selection, and when passed to a variadic function, it ensures a correctly sized null pointer representation is placed on the call stack.

Using nullptr in Practice

You can safely use nullptr anywhere you previously used NULL to initialize or compare pointers.

#include <stdio.h>
#include <stddef.h>

#define GET_TYPE_NAME(x) _Generic((x), \
    int: "int", \
    long: "long", \
    void *: "void *", \
    nullptr_t: "nullptr_t", \
    default: "other" \
)

int main(void) {
    /* Using nullptr to initialize a pointer */
    int *modern_ptr = nullptr;

    if (modern_ptr == nullptr) {
        printf("The pointer is safely grounded.\n");
    }

    /* NULL's type is implementation-defined (often int or void *) */
    printf("Type of NULL: %s\n", GET_TYPE_NAME(NULL));
    
    /* nullptr's type is strictly nullptr_t */
    printf("Type of nullptr: %s\n", GET_TYPE_NAME(nullptr));

    return 0;
}

Why it matters

Using nullptr explicitly tells the compiler and static analysis tools that you are working with a memory address. This eliminates type-matching ambiguities in generic macros and prevents severe undefined behavior when interacting with variadic arguments.

Key takeaway

C23 introduces the built-in nullptr keyword to provide a universally type-safe null pointer constant, replacing the implementation-defined and often ambiguous NULL macro.