Skip to the content of the web site.

Lesson 214: Why do some C++ programs use 0 instead of nullptr for the null pointer?

Previous lesson Next lesson


Up to this point, we have always used nullptr to represent the null pointer. In older C++ programs, however, you may notice that instead of using nullptr, they use what appears to be an integer 0. In the original C++ specification, this was actually the case: 0 was the null pointer; however, with the introduction of the C++ 2011 standard (C++11), a new keyword nullptr was introduced, and the use of 0 as the null pointer was discouraged.

#include <iostream>

void f( int n ) {
	std::cout << "The argument is an integer..." << std::endl;
}

void f( void *n ) {
	std::cout << "The argument is a pointer..." << std::endl;
}

int main();

int main() {
	int n{0};

	// Which 'f(...)' is called?
	f( n );
	f( 0 );
	f( nullptr );

	return 0;
}

How did your compiler interpret 0? This ambiguity is why C++11 introduced the nullptr keyword.

If you are using a pre-C++11 compiler and you never-the-less want to use nullptr for clarity, you can always use:

#define nullptr 0

however, you must be aware that this does not prevent the ambiguity described above.


Previous lesson Next lesson