NULL vs nullptr


Today, our short discussion will revolve around another essential distinction that has emerged within Modern C++. With the introduction of C++11, a new keyword, ‘nullptr,’ was incorporated into the C++ language. This article aims to explore the implications this addition carries and the distinctions it holds in comparison to the conventional ‘NULL.’ We will examine differences one by one.

1. nullptr is included into C++ itself.

Prior to C++11, including the ‘iostream’ header was necessary to utilize ‘NULL.’ However, with the advent of C++11, no header inclusion is required to use ‘nullptr’ as it has been integrated into the language itself.

2. Arithmetics operations are not allowed on nullptr as opposed to NULL since NULL basically means 0.

You can assign a value of NULL to an integer variable, allowing you to perform arithmetic operations using that NULL value. Additionally, you can utilize cout to print this NULL value. However, it’s important to note that nullptr can only be assigned to pointer variables; it cannot be used for arithmetic operations or direct printing using cout.

std::cout << NULL << std::endl;      // will print 0
std::cout << nullptr << std::endl;   // Compile time error

3. Passing them to functions.

If you have a function that accepts an integer value as a parameter, you can actually pass NULL to this function, even though the parameter is of integer type and not a pointer. However, if you attempt to pass nullptr to the same function, you will encounter a compile-time error. This is because nullptr is meant to be used exclusively with pointers, and the compiler will detect this type mismatch and raise an error during compilation.

void foo(int a);

foo(NULL);    // Valid
foo(nullptr); // Invalid, error in compile time

4. In case function overloading.

Lets create a scenario, we overload a function in the way:

void foo(int a);
void foo(int *a);

As we discussed in the previous point, it's possible to pass NULL as an argument to a function that expects a non-pointer parameter. If you were to call the function "foo(NULL)", the version of the function that accepts a non-pointer argument would be invoked. In essence, "foo(NULL)" is not distinct from "foo(0)" in this context. However, if you were to use "foo(nullptr)", it would trigger the version of the function that accepts a pointer argument. This distinction arises because nullptr is specifically designed for use with pointers, while NULL, when passed as an argument, behaves as the literal value 0.

Leave a comment