user5363114
user5363114

Reputation:

Implicit cast of null pointer to bool

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)

Upvotes: 15

Views: 7996

Answers (3)

Bathsheba
Bathsheba

Reputation: 234725

See 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.

Upvotes: 23

mazhar islam
mazhar islam

Reputation: 5619

In C++, the null pointer is defined as

A null pointer constant is an integral constant expression (5.19) rvalue of integer type that evaluates to zero.

That's why,

Foo* foo = nullptr;

is like:

Foo* foo = 0;

Moreover, in C++ zero(0) count as boolean false. So your statement if (foo == nullptr) is valid and same as if (!foo).

Upvotes: 3

dspfnder
dspfnder

Reputation: 1123

if (!foo)

This works fine.

if (foo == nullptr)

This would look more clear to someone reading your code.

Upvotes: 0

Related Questions