I understand that as far as the compiler is concerned, the following lines are equivalent.
if (aPtr) {...}
if (aPtr != NULL) {...}
if (NULL != aPtr) {...}
However, I find the second form a lot more readable than the first form.
The third form has saved me from debugging problems a lot more times than I care to remember. How so?
It's very easy to make the mistake of writing
if (aPtr = NULL) {...}
when you meant to write
if (aPtr != NULL) {...}
You can imagine the bugs arising from that typing error. This error is easily avoided using the third form. The statement
if (NULL = aPtr) {...}
will result in a compiler error.
As a matter of habit, I have adopted writing if (NULL != aPtr)
and if (NULL == aPtr)
for pointer comparisons.
I am interested in finding out what others do for such use cases.
EDIT
Is having a function/macro is_null
a good compromise between if (aPtr)
and if (aPtr != NULL)
?
inline bool is_null(void* p) {return (p == NULL);} /* For C++ */
#define is_null(p) ((p) == NULL) /* For C */