We use a null pointer when we do not have the exact address to assign to a pointer. It is considered a good practice and null is assigned at the time of declaration. Therefore the pointer with a null value is called a null pointer.
Check the C++ example for the null pointer.
1 2 3 4 5 6 7 8 9 10 11 | #include <iostream> using namespace std; int main () { int *ptr = NULL; cout << "Value of NULL pointer: " << ptr ; return 0; } |
Output:
1 | Value of NULL pointer: 0 |
The value of null pointer is 0 as provided in many of the standard library.
We can also check the pointer for null before accessing it. By doing so we can perform error handling. We can do it in a following way.
1 2 3 4 5 6 7 8 9 | if (!ptr) { //if will be executed if pointer is not null .......... } else { ....... } |