for some platforms, NULL not 0x0
From Is NULL in C mandatory / defined to be zero? :
NULL guaranteed to be zero, possibly being cast to (void *) 1 .
C99, Β§6.3.2.3, ΒΆ3
An integer constant expression with a value of 0 or such an expression cast for type void * is called a null pointer constant. (55) If the constant of a null pointer is converted to a type of pointer, the resulting pointer, called the null pointer, is guaranteed to compare unequal to a pointer to any object or function.
And note 55 says:
55) The NULL macro is defined in <stddef.h> (and other headers) as a null pointer constant.
Please note that due to the way the rules for null pointers are formulated, the value you use to assign / compare null pointers is guaranteed to be zero, but the bit pattern actually stored inside the pointer can be any other (but AFAIK only few very esoteric platforms have used this fact, and this should not be a problem, since you should go to UB -land anyway to βseeβ the basic structure of bits).
So, as for the standard, the two forms are equivalent ( !ptr equivalent to ptr==0 due to 6.5.3.3 ΒΆ5, and ptr==0 equivalent to ptr==NULL ); if(!ptr) also pretty idiomatic.
As I said, I usually write if(ptr==NULL) instead of if(!ptr) to make it clear that I am checking for a pointer to nullity instead of some boolean value.
- Note that in C ++,
void * casting cannot be present due to stricter implicit casting rules that will make using such NULL cumbersome (you will have to explicitly convert it to a comparable pointer type each time).
source share