VOOZH about

URL: https://www.geeksforgeeks.org/cpp/understanding-nullptr-c/

⇱ Understanding nullptr in C++ - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Understanding nullptr in C++

Last Updated : 9 Jun, 2026

In C++, NULL was traditionally used to represent null pointers. However, its use can lead to ambiguity in function overloading and unintended type conversions. To overcome these issues, C++11 introduced nullptr, a type-safe keyword that clearly represents a null pointer and eliminates ambiguity in pointer operations.

  • nullptr provides a type-safe null pointer representation
  • It avoids unintended conversions to integer types

Output

cpp:20:8: error: call of overloaded 'fun(NULL)' is ambiguous
20 | fun(NULL);

Explanation

  • NULL is typically defined as 0 or (void*)0
  • It can match both int and pointer types
  • This causes ambiguity in overloaded functions

How nullptr Solves the Problem

Replacing NULL with nullptr removes ambiguity because nullptr is a distinct pointer type.

  • It is not treated as an integer
  • It only matches pointer types
  • It resolves overload conflicts clearly

Output
fun(char*)

Type Safety of nullptr

Unlike NULL, nullptr cannot be assigned to integer types.

Output

Compiler Error

Explanation

  • nullptr is strictly a pointer type
  • It prevents accidental integer assignments
  • This makes code safer and more reliable

nullptr in Conditional Statements

nullptr can be used in conditions to check pointer validity.


Output
false

Explanation: A null pointer evaluates to false in a conditional expression, while a valid pointer evaluates to true.

Comparison Behavior of nullptr 

The nullptr keyword supports safe and well-defined comparisons with pointer types.

  • Can be compared with pointers using == and !=
  • Correctly identifies whether a pointer is null or non-null
  • Can be assigned or compared with any pointer type

nullptr_t Type Behavior

Output

can compare
x is null

Explanation

  • nullptr has a special type nullptr_t
  • Comparisons between nullptr_t values are well-defined
  • Ensures consistent behavior in pointer operations
Comment
Article Tags:
Article Tags: