In C, NULL is defined as (void *)0 whereas in C++ it is 0. Why is it so?
In C I can understand that if NULL is not typecast to (void *) then compilers may/may not generate warning. Other than this, is there any reason?
In C, NULL is defined as (void *)0 whereas in C++ it is 0
Share
Back in C++03, a null pointer was defined by the ISO specification (§4.10/1) as
This is why in C++ you can write
In C, this rule is similar, but is a bit different (§6.3.2.3/3):
Consequently, both
and
are legal. However, my guess is that the
void*cast is here so that statements likeproduce a compiler warning on most systems. In C++, this wouldn’t be legal because you can’t implicitly convert a
void*to another pointer type implicitly without a cast. For example, this is illegal:However, this leads to issues because the code
is legal C++. Because of this and the ensuing confusion (and another case, shown later), since C++11, there is a keyword
nullptrrepresenting a null pointer:This doesn’t have any of the above problems.
The other advantage of
nullptrover 0 is that it plays better with the C++ type system. For example, suppose I have these two functions:If I call
It’s equivalent to
which calls
DoSomething(int)instead of the expectedDoSomething(char*). However, withnullptr, I could writeAnd it will call the
DoSomething(char*)function as expected.Similarly, suppose that I have a
vector<Object*>and want to set each element to be a null pointer. Using thestd::fillalgorithm, I might try writingHowever, this doesn’t compile, because the template system treats
NULLas anintand not a pointer. To fix this, I would have to writeThis is ugly and somewhat defeats the purpose of the template system. To fix this, I can use
nullptr:And since
nullptris known to have a type corresponding to a null pointer (specifically,std::nullptr_t), this will compile correctly.