Is NULL always false?

前端 未结 13 1609
孤城傲影
孤城傲影 2020-11-27 04:44

Is it safe to assume that NULL always translates to false in C?

void *somePtr = NULL;

if (!somePtr) {
  /* This will always be executed? */
}
<         


        
相关标签:
13条回答
  • 2020-11-27 05:41

    Yes, if(!p) is valid and guaranteed to work.

    An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant. 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.

    https://port70.net/~nsz/c/c11/n1570.html#6.3.2.3p3

    This means that (void*)0 is a null pointer. It also means that if p is a pointer, then p==0 is equivalent to p==(void*)0.

    It also means that if p is a not a null pointer, then p==(void*)0 will evaluate to 0.

    So far, so good.

    Conversion of a null pointer to another pointer type yields a null pointer of that type. Any two null pointers shall compare equal.

    http://port70.net/~nsz/c/c11/n1570.html#6.3.2.3p4

    Note that "Any two null pointers shall compare equal." This means that if p is a null pointer, then p==0 will evaluate to true, because 0 will be promoted to (void*)0 which is a null pointer. It also mean that no non-null pointer can be equal to a null pointer.

    Let's have a look at the negation operator.

    The result of the logical negation operator ! is 0 if the value of its operand compares unequal to 0, 1 if the value of its operand compares equal to 0. The result has type int. The expression !E is equivalent to (0==E).

    http://port70.net/~nsz/c/c11/n1570.html#6.5.3.3p5

    This tells us that !p is the same as p==0 by definition, which is the same as p==(void*)0 as mentioned above.

    And taking the fact that all null pointers are equal into consideration, this means that p==(void*)0 can only evaluate to true if p is a null pointer and and only false if p is not a null pointer.

    So yes, if(!p) is a perfectly safe way to check if p is a null pointer or not.

    0 讨论(0)
提交回复
热议问题