Why should we use nullptr instead of NULL or 0?

Jaewon ShinJaewon Shin
1 min read

In modern C++, using nullptr is preferred over NULL or 0 when dealing with pointers.

Here’s why:

  • The type of nullptr is std::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 or 0, the compiler might get confused if a function is overloaded to take either an int 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 over NULL or 0 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.

0
Subscribe to my newsletter

Read articles from Jaewon Shin directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Jaewon Shin
Jaewon Shin