Can I use if (pointer) instead of if (pointer != NULL)?
You can; the null pointer is implicitly converted into boolean false while non-null pointers are converted into true. From the C++11 standard, section on 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 tofalse
; any other value is converted totrue
. A prvalue of typestd::nullptr_t
can be converted to a prvalue of typebool
; the resulting value isfalse
.
Yes, you could.
- A null pointer is converted to false implicitly
- a non-null pointer is converted to true.
This is part of the C++ standard conversion, which falls in Boolean conversion clause:
§ 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.
Yes, you can. In fact, I prefer to use if(pointer)
because it's simpler to read and write once you get used to it.
Also note that C++11 introduced nullptr
which is preferred over NULL
.
Question is answered, but I would like to add my points.
I will always prefer if(pointer)
instead of if(pointer != NULL)
and if(!pointer)
instead of if(pointer == NULL)
:
- It is simple, small
Less chances to write a buggy code, suppose if I misspelled equality check operator
==
with=
if(pointer == NULL)
can be misspelledif(pointer = NULL)
So I will avoid it, best is justif(pointer)
.
(I also suggested some Yoda condition in one answer, but that is diffrent matter)Similarly for
while (node != NULL && node->data == key)
, I will simply writewhile (node && node->data == key)
that is more obvious to me (shows that using short-circuit).- (may be stupid reason) Because NULL is a macro, if suppose some one redefine by mistake with other value.
Explicitly checking for NULL could provide a hint to the compiler on what you are trying to do, ergo leading to being less error-prone.