But sometimes a pointer must explicitly point to nothing, and not just to an invalid address. There definitely can’t be a variable at memory location 0 and for this reason an accidental access via a null pointer would always lead to an immediate crash. This is better than if the pointer points to a random value and the program accidentally continues to work with it without noticing the error.
For such cases, there is a special value that each pointer type can take: the null pointer value. This value can be expressed in two ways in C++. either by a 0 or by the nullptr keyword.
variable-type *pointervar-name = 0;
variable-type *pointervar-name = nullptr;
#include <iostream>
using namespace std;
int main() {
int *ptr = nullptr;
if (!ptr) {
cout << "ptr ist null pointer";
}
}
ptr ist null pointer