NULL appears to be zero in my GCC test programs, but wikipedia says that NULL is only required to point to unaddressable memory.
Do any compilers make NULL non-zero? I’m curious whether if (ptr == NULL) is better practice than if (!ptr).
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
NULLis guaranteed to be zero, perhaps casted to(void *)1.C99, §6.3.2.3, ¶3
And note 55 says:
Notice that, because of how 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 thing (but AFAIK only few very esoteric platforms exploited this fact, and this should not be a problem anyway since to “see” the underlying bit pattern you should go into UB-land anyway).
So, as far as the standard is concerned, the two forms are equivalent (
!ptris equivalent toptr==0due to §6.5.3.3 ¶5, andptr==0is equivalent toptr==NULL);if(!ptr)is also quite idiomatic.That being said, I usually write explicitly
if(ptr==NULL)instead ofif(!ptr)to make it extra clear that I’m checking a pointer for nullity instead of some boolean value.void *cast cannot be present due to the stricter implicit casting rules that would make the usage of suchNULLcumbersome (you would have to explicitly convert it to the compared pointer’s type every time).