if(!ptr)与C中的if(ptr == NULL) [英] if (!ptr) VS if (ptr == NULL) in C

查看:362
本文介绍了if(!ptr)与C中的if(ptr == NULL)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时候我看到程序员使用:

Sometimes I see programmers use:

void *ptr = <something>;
if (ptr == NULL)
    <do something>;

代替:

void *ptr = <something>;
if (!ptr)
    <do something>;

if (!ptr)是否有任何可能出错的地方,还是仅仅是编码样式首选项?

Is there anything that can go wrong with if (!ptr), or is it just a coding style preference?

推荐答案

在C语言中,这只是一个编码样式首选项.

In C, it is just a coding style preference.

有些人更喜欢if (NULL == ptr),其论点是,如果程序员输入错误(并且将==键入为 =),则编译器会抱怨.但是,许多编译器会针对if (ptr=NULL)发出警告(至少是最近的 GCC 会以gcc -Wall -Wextra).

Some people prefer if (NULL == ptr) with the argument that if the programmer made a typo (and mistyped the == as a single =) the compiler will complain. However, many compilers would emit a warning for if (ptr=NULL) (at least recent GCC do, when invoked as gcc -Wall -Wextra as you should).

在C ++中(您将使用nullptr而不是NULL)可能会有所不同,因为可以重新定义operator !(例如,在智能指针上).但是,在原始普通指针(如void*sometype*SomeClass*)上,不能重新定义!!=之类的运算符.

In C++ (where you would use nullptr instead of NULL) there could be a difference, because one can redefine operator ! (e.g. on smart pointers). However, on raw plain pointers (like void*, or sometype* or SomeClass*), you cannot redefine operators like ! or !=.

顺便说一句,有些奇怪的处理器可能具有NULL指针,这些指针不是都是全零位的机器字(但编译器应处理此问题).我不能说出今天广泛使用的任何此类处理器(不过,以1980年代分割为16位x86的处理器为例).

BTW, some weird processors might have NULL pointers which are not an all zero-bits machine word (but the compiler should deal with this issue). I can't name any such processor in wide use today (however think of 1980s segmented 16 bits x86 as a counter example).

这篇关于if(!ptr)与C中的if(ptr == NULL)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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