检查在C / C NULL指针++ [英] Checking for NULL pointer in C/C++

查看:170
本文介绍了检查在C / C NULL指针++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在最近code检讨,一个贡献者试图强制在所有的指针 NULL 检查按以下方式进行:

In a recent code review, a contributor is trying to enforce that all NULL checks on pointers be performed in the following manner:

int * some_ptr;
// ...
if (some_ptr == NULL)
{
    // Handle null-pointer error
}
else
{
    // Proceed
}

而不是

int * some_ptr;
// ...
if (some_ptr)
{
    // Proceed
}
else
{
    // Handle null-pointer error
}

我同意他的方式就是在这个意义上,它的明确的说:请确保此指针不为NULL更加清楚一点,但我会反驳说,说,任何人谁的工作对这个code会理解,使用在如果指针变量声明隐式检查 NULL 。此外,我觉得第二种方法引入之流的错误的几率较小:

I agree that his way is a little more clear in the sense that it's explicitly saying "Make sure this pointer is not NULL", but I would counter that by saying that anyone who's working on this code would understand that using a pointer variable in an if statement is implicitly checking for NULL. Also I feel the second method has a smaller chance of introducing a bug of the ilk:

if (some_ptr = NULL)

这仅仅是找到一个绝对的痛苦和调试。

which is just an absolute pain to find and debug.

哪种方式你preFER为什么?

Which way do you prefer and why?

推荐答案

在我的经验中,表单的测试如果(PTR)如果(!PTR)是preferred。他们不依赖于符号 NULL 的定义。他们不公开为意外分配的机会。他们清楚,简洁。

In my experience, tests of the form if (ptr) or if (!ptr) are preferred. They do not depend on the definition of the symbol NULL. They do not expose the opportunity for the accidental assignment. And they are clear and succinct.

编辑:作为肥皂盒在评论中指出的那样,他们是用C ++类兼容,如的auto_ptr 是充当指针对象和它提供了一个转换布尔启用正是这个成语。对于这些对象,明确的比较 NULL 将不得不调用转换为指针,可能有其他的语义副作用或会比简单的存在性检查更昂贵的布尔转换暗示。

As SoapBox points out in a comment, they are compatible with C++ classes such as auto_ptr that are objects that act as pointers and which provide a conversion to bool to enable exactly this idiom. For these objects, an explicit comparison to NULL would have to invoke a conversion to pointer which may have other semantic side effects or be more expensive than the simple existence check that the bool conversion implies.

我有code,说这是什么意思没有不需要的文本的preference。 如果(PTR!= NULL)的含义如果(PTR),但在冗余特异性的费用相同。接下来顺理成章的事情就是写 IF((PTR!= NULL)== TRUE)和出路在于疯狂。 C语言显然,如果,测试一个布尔值,而或类似的具有非零的具体含义值是true,零是假的。冗余不使其更清晰。

I have a preference for code that says what it means without unneeded text. if (ptr != NULL) has the same meaning as if (ptr) but at the cost of redundant specificity. The next logical thing is to write if ((ptr != NULL) == TRUE) and that way lies madness. The C language is clear that a boolean tested by if, while or the like has a specific meaning of non-zero value is true and zero is false. Redundancy does not make it clearer.

这篇关于检查在C / C NULL指针++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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