How Not To Test Pointers
Pointer tests in the realm of implementation-dependent behavior
So, what’s wrong with this little snippet of code:
extern void *foo();
void *p = foo();
if( p > 0 )
{
printf( “Pointer is okay\n” );
}
When I saw this, my first thought was that I’d never seen that done, nor had I ever imagined anyone doing it.
The compiler apparently liked it just fine, but the behavior was not what the person who wrote that line of code expected – i.e. the conditional evaluated false on a non-null pointer.
According to H&S , the behavior in this case is undefined unless the pointers being compared point into the same array or structure.
Bottom line – don’t do that! The normal four ways to test a pointer always work.
if( p )
if( ! p )
if( p == 0 )
if( p != 0 )
(And, no, this wasn’t my code! 🙂