Syntax of Null Pointer in C++
We can create a NULL pointer of any type by simply assigning the value NULL to the pointer as shown:
int* ptrName = NULL; // before C++11
int* ptrName = nullptr
int* ptrName = 0; // by assigning the value 0
A null pointer is represented by the value 0 or by using the keyword NULL. With the new versions of C++ like C++11 and later, we can use “nullptr” to indicate a null pointer.
Checking NULL Pointer
We can check whether a pointer is a NULL pointer by using the equality comparison operator.
ptrName == NULL
or
ptrName == nullptr
The above expression will return true if the pointer is a NULL pointer. False otherwise.
NULL Pointer in C++
A NULL Pointer in C++ indicates the absence of a valid memory address in C++. It tells that the pointer is not pointing to any valid memory location In other words, it has the value “NULL” (or ‘nullptr’ since C++11). This is generally done at the time of variable declaration to check whether the pointer points to some valid memory address or not. It is also returned by several inbuilt functions as a failure response.
Trying to dereference a NULL pointer i.e. trying to access the memory it points to leads to some undefined behavior leading to the program crash.