First, to be 100% clear, there is no difference between C and C++ here. And second, the Stack Overflow question you cite doesn't talk about null pointers; it introduces invalid pointers; pointers which, at least as far as the standard is concerned, cause undefined behavior just by trying to compare them. There is no way to test in general whether a pointer is valid.
In the end, there are three widespread ways to check for a null pointer:
if ( p != NULL ) ...
if ( p != 0 ) ...
if ( p ) ...
All work, regardless of the representation of a null pointer on the
machine. And all, in some way or another, are misleading; which one you
choose is a question of choosing the least bad. Formally, the first two
are indentical for the compiler; the constant NULL
or 0
is converted
to a null pointer of the type of p
, and the results of the conversion
are compared to p
. Regardless of the representation of a null
pointer.
The third is slightly different: p
is implicitly converted
to bool
. But the implicit conversion is defined as the results of p
!= 0
, so you end up with the same thing. (Which means that there's
really no valid argument for using the third style—it obfuscates
with an implicit conversion, without any offsetting benefit.)
Which one of the first two you prefer is largely a matter of style,
perhaps partially dictated by your programming style elsewhere:
depending on the idiom involved, one of the lies will be more bothersome
than the other. If it were only a question of comparison, I think most
people would favor NULL
, but in something like f( NULL )
, the
overload which will be chosen is f( int )
, and not an overload with a
pointer. Similarly, if f
is a function template, f( NULL )
will
instantiate the template on int
. (Of course, some compilers, like
g++, will generate a warning if NULL
is used in a non-pointer context;
if you use g++, you really should use NULL
.)
In C++11, of course, the preferred idiom is:
if ( p != nullptr ) ...
, which avoids most of the problems with the other solutions. (But it is not C-compatible:-).)