How to check if a pointer is NULL in C++

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++.

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:

Output:

It is not a NULL Pointer.

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:

Output:

It is not a NULL Pointer

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:

Output:

It is a NULL Pointer
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.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *