C/C++: ordered comparison between pointers and zero, actually with NULL

A few days ago I faced this piece of code in Erlang/OTP 19.3.2 with a fatal error message of LLVM 4.0 clang compiler when compiling it on FreeBSD 11.0-STABLE:

void *temp;
if (temp > NULL) { // do something ... }

Comparing a pointer with NULL looks legit. NULL means a non-existent value or unallocated object as a pointer, so comparing a pointer with it means determining whether the pointer is linked to a valid object or not. The macro NULL in C is usually defined as zero, or a pointer cast from the value zero.

Comparing which is large or small between a pointer and NULL , however, looks completely illogical. Ordered comparison of two valid pointers is legit, but no pointer will be smaller than NULL , so comparing if a pointer is larger than NULL simply means if the pointer is not NULL.

And of course you cannot meaningfully compare two pointers of different types of data.

So I made a small fix as:

void *temp;
if (temp != (void *) NULL) { // do something ... }

And the compilation passed without the error.

Lessons I learned?

  • Some people try to compare the order of pointer with NULL;
  • Don’t take anything for granted; and
  • Even many modern C or C++ compilers simply pass invalid or redundant ordered comparison of pointers with NULL without any compilation errors if the semantic meaning of the incomplete piece of code is unambiguous.

For the further details, check out: