4

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?

Jules Lamur
  • 2,078
  • 1
  • 15
  • 25

2 Answers2

10

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.

alain
  • 11,939
  • 2
  • 31
  • 51
2

According the standard and this answers (Implicit cast of null pointer to bool) the two syntax have the same behavior

Community
  • 1
  • 1
baddger964
  • 1,199
  • 9
  • 18