0

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,

  1. 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.
  1. 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.)

op ol
  • 705
  • 4
  • 11
  • 2
    6.5.9,5 describes comparison of a pointer and a null pointer constant. Through that rule, both `ptr == 0` and `(void*)0 == 0` are defined (with the obvious meanings). – Paul Hankin Mar 19 '21 at 10:51
  • 2
    Just to be clear, you can use 0 or NULL, and they compare equal to each other, and comparing either to a pointer tells you if the pointer is a null pointer or not. I think the part you were missing was 6.5.9.5 which describes how == works when one of the operands is a pointer and the other a null pointer constant (converting the null pointer constant into the type of the pointer before comparison occurs). – Paul Hankin Mar 19 '21 at 10:56
  • @Paul Hankin Thanks a lot! The 6.5.9.5 exactly says 0 is the same as NULL when using '==' with a null pointer. I saw that but couldn't catch the point. Now I can be sure. Anyway I don't think my question is duplicated by above link. – op ol Mar 19 '21 at 11:00
  • 2
    I think there's enough overlap between your question and the linked question and top answer that it's ok for it to be a dupe. Perhaps if this question were cut down to the a specific (and technical) point about the application of the standard to `ptr == 0` then it would be different, but to be honest I don't think it's worth anyone's time, and you got your answer. – Paul Hankin Mar 19 '21 at 11:28

0 Answers0