Skip to the content of the web site.

Lesson 202: What is the difference between NULL, 0 and nullptr?

Previous lesson Next lesson


If you are familiar with the C programming language, you will see that the null pointer is always represented by the macro NULL. It is not defined by default, but rather it is defined in many libraries. You can define this macro as follows:

#ifndef NULL
	#define NULL ((void*)0)
#endif

That is, it is 0 cast as a void pointer.

With the introduction of C++, the original idea was to replace NULL by simply allowing 0 to be interpreted as the null pointer. Thus, in many pre-C++11 programs, you will see 0 being used wherever we use nullptr.

In C++11, however, it was decided to introduce a new keyword nullptr to represent the null pointer. One issue is suppose you had a function that was overloaded:

void f( int n ) {
	// Do something with an integer
}

void f( int *p_n ) {
	// Do something with a poitner to an integer
}

Which one is called if you call f(0)? The explicit keyword nullptr now makes it possible to distinguish between f(0) calling the first and f(nullptr) calling the second.

You can, however, still assign 0 or NULL to a pointer; although, this is discouraged.


Previous lesson Next lesson