Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check pointer's nullability: !pointer or pointer == nullptr? [duplicate]

Tags:

c++

pointers

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?

like image 613
Jules Lamur Avatar asked Dec 18 '22 07:12

Jules Lamur


2 Answers

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.

like image 147
alain Avatar answered Dec 20 '22 21:12

alain


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

like image 22
baddger964 Avatar answered Dec 20 '22 22:12

baddger964