In C++, pointers are not safe inherently. When we dereference a pointer, it is our responsibility to ensure that it points at a valid address.
In this article, we will discuss three methods to check if a pointer is NULL in C++.
Table of Contents
Comparison with nullptr
In C++, we can initialize a pointer by assigning the value ‘0’ or the literal ‘nullptr’.
Note: Modern C++ suggests that we should not initialize the pointers to 0. It can lead to different results when we do function overloading. In this method, we will check if the pointer is not equal to
nullptr
. If the condition is true, then the statements will be executed.
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#include <iostream> using namespace std; int main() { int i = 10; int *ptr = &i if(ptr != nullptr) { cout << "It is not NULL Pointer" << endl ; } else { cout << "It is a NULL Pointer" << endl; } return 0; } |
Output:
Comparison with 0
In C++, there is constant NULL
which has a value of zero. A pointer can be assigned to 0
or NULL
. It is not recommended to assign 0 to a pointer because it can give undesired results. But, we can still check if a pointer is null or not by comparing it with 0.
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#include <iostream> using namespace std; int main() { int i = 10; int *ptr = &i if(ptr != 0) { cout << "It is not NULL Pointer" << endl ; } else { cout << "It is a NULL Pointer" << endl; } return 0; } |
Output:
Using the value of pointer as a condition
In C++, if you use a null pointer in logical expression, then they will be evaluated as false. We can pass the given pointer in the if
condition to check if it is null or not.
Note: Sometimes dereferencing a null pointer can lead to undesired results and behaviour which can also terminate the program abnormally.
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
#include <iostream> using namespace std; int main() { int i = 10; int *ptr1 = nullptr; int *ptr2= &i; //checking for ptr1 if(ptr1) { cout << "It is not NULL Pointer" << endl ; } else { cout << "It is a NULL Pointer" << endl; } //checking for ptr2 if(ptr2) { cout << "It is not NULL Pointer" << endl ; } else { cout << "It is a NULL Pointer" <<endl ; } return 0; } |
Output:
It is not a NULL Pointer
Conclusion
In this article, we discussed the methods to check if the pointer is null. We should check if the pointer is null for handling the errors in the pointers code. For example, we will dereference a pointer only if it is not NULL.