In C++11 and later versions, nullptr
is a special literal that represents a null pointer (i.e., a pointer that does not point to a valid address)
Before C++11, we had to use NULL
or 0
. But this led to ambiguity errors, especially when working with overloaded functions and templates.
Additionally, it improves readability and helps prevent difficult-to-detect errors related to memory management.
It is recommended to use nullptr
whenever possible instead of NULL
or 0
to represent null pointers.
Declaration of null pointers
To declare a null pointer in C++11 and later versions, we simply initialize it to nullptr
. This ensures that the pointer does not have a valid address assigned.
#include <iostream>
int main() {
int* ptr = nullptr; // Pointer to int initialized to nullptr
if (ptr == nullptr) {
std::cout << "The pointer does not point to any valid address." << std::endl;
}
return 0;
}
Here,
- The pointer
ptr
is declared and initialized withnullptr
- This means it has no valid memory address assigned.
Advantages of nullptr
The main advantage of nullptr
lies in its ability to enhance the safety and clarity of the code. For example, let’s imagine this scenario,
#include <iostream>
void func(int x) {
std::cout << "func(int) called with " << x << std::endl;
}
void func(int* ptr) {
if (ptr) {
std::cout << "func(int*) called with valid pointer." << std::endl;
} else {
std::cout << "func(int*) called with null pointer." << std::endl;
}
}
int main() {
func(0); // Ambiguous with NULL, interpreted as `func(int)`
func(nullptr); // Clear: calls `func(int*)` with null pointer
return 0;
}
In this example,
func(0)
can be ambiguous, as0
could be interpreted as an integer rather than a pointer.- With
nullptr
, there is no ambiguity:func(nullptr)
calls the overload that accepts a pointer (func(int*)
)