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 null pointer constant is converted to a pointer type, 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 several very esoteric platforms have used this fact, and this should by no means be a problem, since you must enter UB to “see” the basic bit diagram - anyway).
So, with regard to the standard, 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.
In doing so, I usually write explicitly 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.
- Please note that in C ++, the
void * butt cannot be present due to more stringent implicit casting rules that will make using such NULL cumbersome (you will have to explicitly convert it to a comparable pointer type each time).
Matteo Italia Nov 27 '11 at 19:52 2011-11-27 19:52
source share