DEV Community

Haris
Haris

Posted on

Null Pointer

The main reason to use nullptr over NULL or 0 is that the nullptr is of type std::nullptr_t this is very useful in case of function overloading.

Consider this example:

void func(int);

void func(bool);

void func(void*);
Enter fullscreen mode Exit fullscreen mode

Now if we call the functions by the following arguments:

  • func(0) -> This will call func(int) not func(void*)
  • func(NULL)-> This will also call func(int)

So why does NULL also calls func(int)?
This is because NULL's possible implementation is: #define NULL 0 Or depending on your compiler in modern C++ version it can be #define NULL nullptr so just to be on the safe side always use 'nullptr'.

In case of pointer type (int*) the compiler correctly deduces the integer 0 to be a null pointer but like above in case of function overloading where a function overload with integer already exists will always overshadow the pointer argument overload.

Readability And Clarity

Another important thing that nullptr does well is readability along with auto keyword, consider this example:

auto result = findRecord(…);

if(result == 0) {…}

if(result == nullptr) {…}
Enter fullscreen mode Exit fullscreen mode

See how the last statement gives more clarity to the reader that result is of type pointer.

Fun Fact
When you create a new object on heap which is a non-temporary object, however the pointer you get from new is an r-value but it can still point to an l-value.
Dereferencing pointers always create l-value references, notably the object created using new is also an l-value because it has an address.

Top comments (0)