Nowadays, with C++11, Whats recommended to use, Zero
or NULL
? The first of the second if?
int * p = getPointer();
if( 0 == p ){
// something
}
if( NULL == p ){
// something
}
UPDATE: I forget the new
if( nullptr == p ){
// something
}
UPDATE 2: the examples are to show the options to write null pointer, I know is more pleasant to write if( !p )
.
NULL is use as an abstraction because at the time it was not clear what the value of NULL would be from system to system. So the standard value is zero, Which is the same for '0'. Using NULL or '0' you are sure your code would work on any system regardless of what their values are.
As I mentioned above, the general rule of thumb that I recommend is that you should start using nullptr whenever you would have used NULL in the past. As a reminder, since C++11, NULL can be either an integer literal with value zero, or a prvalue of type std::nullptr_t .
No its not the same as null means a value that is unavailable unassigned or unknown and zero is a defined value.
The C standard defines that 0 is typecast to (void *) is both a null pointer and a null pointer constant.
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 <class T>
void display(T)
{
std::cout << type_name<T>() << '\n';
}
template <class T>
void
f(T&& t)
{
display(std::forward<T>(t)); // "perfectly forward" T
}
int main()
{
f(0);
f(NULL);
f(nullptr);
}
With an appropriate definition of type_name<T>()
, 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.
Neither, it's nullptr
.
Though, in your case, I'd just go with
if ( !p ){
//something
}
1 The pointer literal is the keyword
nullptr
. It is a prvalue of typestd::nullptr_t
. [ Note:std::nullptr_t
is a distinct type that is neither a pointer type nor a pointer to member type; rather, a prvalue of this type is a null pointer constant and can be converted to a null pointer value or null member pointer value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With