NULL 总是假的吗? [英] Is NULL always false?

查看:38
本文介绍了NULL 总是假的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设 NULL 在 C 中总是转换为 false 是否安全?

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

void *somePtr = NULL;

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

还是应该对 NULL 的值进行显式检查?

Or should an explicit check against the value of NULL be made?

推荐答案

是的.NULL 评估为假,因为 C 认为任何非零值为真,任何零值都为假.NULL 本质上是 zero 地址,在比较中被视为这样,我相信会被提升为 int 以进行布尔检查.我希望熟悉 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++ 编程中,两个 null指针保证比较平等的;ANSI C 保证任何空指针在 a 中将等于 0与整数类型比较;此外,宏 NULL 被定义作为空指针常量,即值 0(作为整数类型或转换为指向 void 的指针),因此空指针将比较等于空.

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.

参考:http://en.wikipedia.org/wiki/Null_pointer#Null_pointer

这篇关于NULL 总是假的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆