Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is if(pointerVar) the same as if(pointerVar!=NULL)?

Tags:

c++

pointers

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

like image 242
Alexander Rafferty Avatar asked Feb 11 '11 05:02

Alexander Rafferty


1 Answers

For the most pedantic answer, here's the relevant sections of the spec.

First, here's how if statements work, from §6.4.4:

The value of a condition that is an initialized declaration in a statement other than a switch statement is the value of the declared variable implicitly converted to type bool. If that conversion is ill-formed, the program is ill-formed.

"But how are pointers converted to bools?" you may ask. Well, here's §4.12.1: :-)

An rvalue of arithmetic, enumeration, pointer, or pointer to member type can be converted to an rvalue 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.

So this means that the statement

if (ptr)

is equivalent to

if ((bool) ptr)

which is in turn equivalent to

if (ptr == NULL)

But what about

if (!ptr)

Well, the C++ spec, §5.3.1.8, says that

The operand of the logical negation operator ! is implicitly converted to bool (clause 4); its value is true if the converted operand is false and false otherwise. The type of the result is bool.

So this means that

if (!ptr)

is equivalent to

if (!(bool)ptr)

which is in turn equivalent to

if (!(ptr == NULL))

which is finally equivalent to

if (ptr != NULL)

Whew! That was a fun search to do. Hope this answers your question!

Of course, there is more to this story. NULL is not part of the C++ language; it's a macro in <cstddef> defined as

#define NULL 0

This works because the C++ standard defines the null pointer in §4.10.1 as

A null pointer constant is an integral constant expression (5.19) rvalue of integer type that evaluates to zero. A null pointer constant can be converted to a pointer type; the result is the null pointer value of that type and is distinguishable from every other value of pointer to object or pointer to function type

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.

like image 194
templatetypedef Avatar answered Sep 28 '22 07:09

templatetypedef