gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 17:19:38 24 4
gpt4 key购买 nike

我知道 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.

关于相比之下,我可以假设 NULL 值为假吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28856825/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com