为NULL总是假的? [英] Is NULL always false?
问题描述
它是安全的假设, NULL
总是转换为false用C?
Is it safe to assume that NULL
always translates to false in C?
void *somePtr = NULL;
if (!somePtr) {
/* This will always be executed? */
}
还是应该对价值的明确检查 NULL
进行?
推荐答案
是的。 NULL计算结果为false,由于C认为任何非零值true任何零值false。 NULL本质上是零
地址,并在比较中也可以这样处理,我相信会被提升到了布尔检查一个int。我希望,你的code是可读的任何人熟悉C,虽然我可能会做出明确的检查
Yes. NULL evaluates to false, since C considers any non-zero value true and any zero value false. NULL is essentially the zero
address and is treated as such in comparisons, and I believe would be promoted to an int for the boolean check. I would expect that your code is readable to anyone familiar with C although I would probably make the check explicit.
在C和C ++编程,两个空
指针保证比较
等于; ANSI C保证任何空
指针将等于0的
一个整型比较;
此外,宏NULL被定义
作为一个空指针常数,即
0值(无论是作为一个整数类型或
转换为一个指向void),因此
空指针将相当于
NULL。
In C and C++ programming, two null pointers are guaranteed to compare equal; ANSI C guarantees that any null pointer will be equal to 0 in a comparison with an integer type; furthermore the macro NULL is defined as a null pointer constant, that is value 0 (either as an integer type or converted to a pointer to void), so a null pointer will compare equal to NULL.
参考:<一href=\"http://en.wikipedia.org/wiki/Null_pointer#Null_pointer\">http://en.wikipedia.org/wiki/Null_pointer#Null_pointer
这篇关于为NULL总是假的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!