In a C++ program, if I want to use a c function that will return NULL for any error, should I check for nullptr
or NULL
?
int * ptr = someCfunction();
if (ptr == nullptr)
return false;
or:
int * ptr = someCfunction();
if (ptr == NULL)
return false;
Which one is better in terms of style?
nullptr is a keyword that represents zero as an address (its type is considered a pointer-type), while NULL is the value zero as an int . If you're writing something where you're referring to the zero address, rather than the value zero, you should use nullptr .
At a very high level, we can think of NULL as a null pointer which is used in C for various purposes.
nullptr is a keyword that can be used at all places where NULL is expected. Like NULL, nullptr is implicitly convertible and comparable to any pointer type. Unlike NULL, it is not implicitly convertible or comparable to integral types.
Nullptr vs NULL NULL is 0 (zero) i.e. integer constant zero with C-style typecast to void* , while nullptr is prvalue of type nullptr_t , which is an integer literal that evaluates to zero.
From the cppreference on nullptr, you can see that there is implicit conversion from nullptr
to NULL
. So you can do either but (as good practice) better use nullptr
from C++11 onwards.
The keyword
nullptr
denotes the pointer literal. It is a prvalue of typestd::nullptr_t
. There exist implicit conversions fromnullptr
to null pointer value of any pointer type and any pointer to member type. Similar conversions exist for any null pointer constant, which includes values of typestd::nullptr_t
as well as the macroNULL
.
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