Null Pointers

A null value is a special value that means that the pointer is not pointing to anything. A pointer holding a null value is called a null pointer. In C/C++, we can assign a pointer a null value like below:

int *ptr(0);  // ptr is now a null pointer
int *ptr(NULL); // assign address 0 to ptr

In C, defines a special preprocessor macro called NULL and the value is 0. It is not part of C++ technically. So try to avoid using this in C++. Note that the value of 0 isn’t a pointer type and assigning 0 to the pointer is not technically correct, because the compiler can’t tell whether we mean a null pointer or the integer 0.


To resolve these issues, C++11 introduces a new keyword called nullptr. nullptr is both a keyword and an rvalue constant, much like the boolean keywords true and false are.

int *ptr = nullptr;

C++ will implicitly convert nullptr to any pointer type. So in the above example, nullptr is implicitly converted to an integer pointer, and then the value of nullptr (0) assigned to ptr.

For Example:

#include <iostream>
 
void checkPtr(int *ptr) {

    if (ptr)
        std::cout << "You passed in " << *ptr << '\n';
    else
        std::cout << "You passed in a null pointer\n";
}
 
int main()
{
    int *myPtr = nullptr;
 
   checkPtr(myPtr); // the argument is definitely a null pointer (not an integer)
 
    return 0;
}

C++11 also introduces a new type called std::nullptr_t and it is not a value. It can only hold one value called nullptr. It will be useful when you whant to write a function that accepts a nullptr argument.

For Example:

#include <iostream>
#include <cstddef> // for std::nullptr_t
 
void checkPtr(std::nullptr_t ptr)
{
    std::cout << "checkPtr() Called\n";
}
 
int main()
{
    checkPtr(nullptr); // call checkPtr with an argument of type std::nullptr_t
 
    return 0;
}

Note: In C++11, use nullptr to initialize the pointer not the keyword NULL.