14

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)
Deantwo
  • 1,113
  • 11
  • 18
  • Both are fine and is more a coding style issue. Follow the style of existing code or if it's your code use which ever is clearer to you. – Richard Critten Nov 02 '15 at 10:31

3 Answers3

23

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.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
3

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

mazhar islam
  • 5,561
  • 3
  • 20
  • 41
0
if (!foo)

This works fine.

if (foo == nullptr)

This would look more clear to someone reading your code.

dspfnder
  • 1,135
  • 1
  • 8
  • 13