I was confused if I can use if(ptr == 0)
for if(ptr == NULL)
. I found there are many questions and answers to this. They said 1. All null pointers compare same. 2. A null pointer is not guaranteed to have all bits set to zero. But I doubt that can be an answer to the question because...
According to 6.3.2.3 p3 and p4 in C99,
- An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant. 55) If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guaranteed to compare unequal to a pointer to any object or function.
- Conversion of a null pointer to another pointer type yields a null pointer of that type. Any two null pointers compare equal.
0
is a null pointer constant, and NULL
in 'stddef.h' is a null pointer constant(0
or (void *)0
). The comparison between 0
and (void *)0
or a null pointer is not defined(the standard just says any two null pointers compare equal).
Then is it really safe to use if(ptr == 0)
instead of if(ptr == NULL)
when checking a validity of a pointer? (finally I want to use if(!ptr)
and I know the original form is good for readability.)