相比之下,我可以假设 NULL 值为假吗?

Can I assume NULL value in comparison as the false?

我知道 NULL == (void *)0 但有人提到它可以表示为不包含全零的值。令我困扰的是,如果这些代码片段对所有 (any_type *):

都是等价的
any_type *val;

if (val) { ... };

if (val != NULL) { ... };

是的。你可以这样使用宏NULL。它是一个空指针常量,等于 0

comp.lang.c FAQ list · Question 5.3:

When C requires the Boolean value of an expression, a false value is inferred when the expression compares equal to zero, and a true value otherwise. That is, whenever one writes

if(expr)

where expr is any expression at all, the compiler essentially acts as if it had been written as

if((expr) != 0)

Substituting the trivial pointer expression p for expr, we have

if(p)   is equivalent to    if(p != 0)

and this is a comparison context, so the compiler can tell that the (implicit) 0 is actually a null pointer constant, and use the correct null pointer value. There is no trickery involved here; compilers do work this way, and generate identical code for both constructs. The internal representation of a null pointer does not matter.


but it is mentioned that it can be represented as a value which doesn't contain all zeros.

是的。真的。但是 representation doesn't matter 在这种情况下:

Whenever a programmer requests a null pointer, either by writing 0 or NULL, it is the compiler's responsibility to generate whatever bit pattern the machine uses for that null pointer.