Namespaces
Variants
Views
Actions

Predefined null pointer constant (since C23)

From cppreference.com
< c‎ | language

Contents

[edit] Syntax

nullptr (since C23)

[edit] Explanation

The keyword nullptr denotes a predefined null pointer constant. It is a non-lvalue of type nullptr_t. nullptr can be converted to a pointer types or bool, where the result is the null pointer value of that type or false respectively.

[edit] Example

Demonstrates that a copy of nullptr can also be used as a null pointer constant.

#include <stddef.h>
#include <stdio.h>
 
void g(int*)
{
    puts("Function g called");
}
 
#define DETECT_NULL_POINTER_CONSTANT(e) \
    _Generic(e,                         \
        void* : puts("void*"),          \
        nullptr_t : puts("nullptr_t"),  \
        default : puts("integer")       \
    )
 
int main()
{
    g(nullptr);         // Fine
    g(NULL);            // Fine
    g(0);               // Fine
 
    puts("-----------------");
 
    auto cloned_nullptr = nullptr;
    auto cloned_NULL    = NULL;
    auto cloned_zero    = 0;
    g(cloned_nullptr);  // Fine
//  g(cloned_NULL);     // ERROR
//  g(cloned_zero);     // ERROR
 
    puts("-----------------");
 
    DETECT_NULL_POINTER_CONSTANT(((void*)0));
    DETECT_NULL_POINTER_CONSTANT(0);
    DETECT_NULL_POINTER_CONSTANT(nullptr);
    DETECT_NULL_POINTER_CONSTANT(NULL); // implementation-defined
}

Possible output:

Function g called
Function g called
Function g called
-----------------
Function g called
-----------------
void*
integer
nullptr_t
void*

[edit] Keywords

nullptr

[edit] References

  • C23 standard (ISO/IEC 9899:2023):

[edit] See also

implementation-defined null pointer constant
(macro constant) [edit]
the type of the predefined null pointer constant nullptr
(typedef) [edit]
C++ documentation for nullptr