Is NULL always false?

前端 未结 13 1623
孤城傲影
孤城傲影 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:18

    My copy of ISO/IEC 9899:TC3 (Committee Draft — Septermber 7, 2007) says:

    6.3 Conversions

    1 Several operators convert operand values from one type to another automatically.

    6.3.2.3 Pointers

    3 An integer constant expression with the value 0 [...] 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.

    So far, ptr!=0 is true (1) for every non-null ptr, but it's still open, how two null pointers compare.

    6.5.9 Equality operators

    5 [...] If one operand is a pointer and the other is a null pointer constant, the null pointer constant is converted to the type of the pointer.

    6 Two pointers compare equal if and only if both are null pointers, both are [...]

    Hence, ptr==0 is 1 (and ptr!=0 is 0), if and only if ptr is a null pointer.

    6.5.3.3 Unary arithmetic operators

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

    So the same holds for !ptr.

    6.8.4.1 The if statement

    1 The controlling expression of an if statement shall have scalar type.

    2 In both forms, the first substatement is executed if the expression compares unequal to 0.

    Note, that a scalar type is an arithmetic type or a pointer type (see "6.2.5 Types", clause 21). Putting it together, we have:

    • if (ptr) succeeds ⇔ ptr!=0 is 1 ⇔ ptr is not a null pointer.
    • if (!ptr) succeeds ⇔ ptr==0 is 1 ⇔ ptr is a null pointer.

提交回复
热议问题