Suppose I have Foo* foo = nullptr;
If I'm checking whether or not foo
is nullptr
, am I permitted to write
if (!foo)
or should I write
if (foo == nullptr)
See Question&Answers more detail:osSuppose I have Foo* foo = nullptr;
If I'm checking whether or not foo
is nullptr
, am I permitted to write
if (!foo)
or should I write
if (foo == nullptr)
See Question&Answers more detail:osSee this standard reference (bold emphasis mine):
C++11 §4.12 Boolean conversions
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. A prvalue of type std::nullptr_t can be converted to a prvalue of type bool; the resulting value is false.
The middle sentence is relevant: it is telling you that the null pointer value (foo = nullptr
) can be implicitly cast to false
which itself has type bool
. Therefore if (!foo)
is well-defined.