Suppose I have a pointer: int *pointer
.
If I want to test its nullability, should I do it with:
bool nullability = !pointer;
Or with:
bool nullability = (pointer == nullptr);
Are both expressions equivalent? If not, why and what are the side effects?
Both are equivaluent because nullptr
is guaranteed to be converted to false
when converted to a boolean.
From N4296:
4.12 Boolean conversions
1 A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a prvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true. For direct-initialization (8.5), a prvalue of type std::nullptr_t can be converted to a prvalue of type bool; the resulting value is false.
According the standard and this answers (Implicit cast of null pointer to bool) the two syntax have the same behavior
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