Nowadays, with C++11, Whats recommended to use, Zero
or NULL
? The first of the second if?
int * p = getPointer();
if( 0 == p ){
//
The other answers are right. But I wanted to say a little more about why nullptr
is better.
In C++11 "perfect forwarding" is very important. It is used everywhere. Obvious places are bind
and function
. But it is also used in a multitude of other places under the covers. But "perfect forwarding" isn't perfect. And one of the places it fails is null pointer constants.
template
void display(T)
{
std::cout << type_name() << '\n';
}
template
void
f(T&& t)
{
display(std::forward(t)); // "perfectly forward" T
}
int main()
{
f(0);
f(NULL);
f(nullptr);
}
With an appropriate definition of type_name
, on my system this prints out:
int
long
std::nullptr_t
This can easily make the difference between working code and errors. With any luck your errors will come at compile time (with horrible error messages). But you may also get run time errors in some circumstances.
Aggressively ban use of 0 and NULL in your code.
Even if you're not perfect forwarding in your code, code you call (such as the std::lib) is very likely using it under the covers.