Simple question:
Is if (pointerVar) the same as if (pointerVar!=NULL)?
Also, is if (!pointerVar) the same as if (pointerVar==NULL)?
Give me your most technically correct/pedantic answer. The two statements seem and make sense to operate the same. Is there anything wrong with the former though (besides its slightly lower readability)?
For the most pedantic answer, here’s the relevant sections of the spec.
First, here’s how
ifstatements work, from §6.4.4:“But how are pointers converted to
bools?” you may ask. Well, here’s §4.12.1: 🙂So this means that the statement
is equivalent to
which is in turn equivalent to
But what about
Well, the C++ spec, §5.3.1.8, says that
So this means that
is equivalent to
which is in turn equivalent to
which is finally equivalent to
Whew! That was a fun search to do. Hope this answers your question!
Of course, there is more to this story.
NULLis not part of the C++ language; it’s a macro in<cstddef>defined asThis works because the C++ standard defines the null pointer in §4.10.1 as
So to be more correct, I should have been using the numeric literal 0 in the above examples. However, if you have
<cstddef>included, then this works out to the same code after preprocessing.