Why should we use nullptr instead of NULL or 0?

In modern C++, using nullptr
is preferred over NULL
or 0
when dealing with pointers.
Here’s why:
The type of
nullptr
isstd::nullptr_t
.std::nullptr_t
can be implicitly converted to any pointer type, but not to an integer.Because of this,
nullptr
behaves like a universal pointer — it works with all raw pointer types, without introducing ambiguity.
🔸 Benefits of nullptr
Avoids overload resolution issues: When passing
NULL
or0
, the compiler might get confused if a function is overloaded to take either anint
or a pointer.nullptr
solves this problem.Improves code clarity: Especially when used with
auto
,nullptr
makes the programmer’s intent clearer — you're assigning a null pointer, not a zero value.
💡 Things to Remember
Always prefer
nullptr
overNULL
or0
in C++11 and later.Avoid overloading functions on pointer and integer types — it leads to confusing and error-prone code.
✅ Example
cppCopyEditvoid process(int);
void process(char*);
process(0); // Calls process(int) — maybe not what you intended
process(NULL); // Still might call process(int), depending on the platform
process(nullptr); // Always calls process(char*) — clear and unambiguous
✍️ Final Tip
Using nullptr
is a small but powerful habit that helps you write cleaner, safer, and more modern C++ code.
Subscribe to my newsletter
Read articles from Jaewon Shin directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
