我可以使用if(指针)而不是if(pointer!= NULL)? [英] Can I use if (pointer) instead of if (pointer != NULL)?

查看:797
本文介绍了我可以使用if(指针)而不是if(pointer!= NULL)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过简单地写 if(pointer)或者我可以检查不是 NULL 的指针是否安全必须使用 if(pointer!= NULL)

Is it safe to check a pointer to not being NULL by writing simply if(pointer) or do I have to use if(pointer != NULL)?

推荐答案

能够;空指针隐式转换为布尔值,而非空指针转换为true。从C ++ 11标准中,布尔转换部分:

You can; the null pointer is implicitly converted into boolean false while non-null pointers are converted into true. From the C++11 standard, section on Boolean Conversions:


算术,无范围枚举,指针或指向成员类型的指针可以转换为类型
bool
prvalue。零值,空指针值或空成员指针值将转换为
false ;
任何其他值转换为
true
。类型$ pr $ b std :: nullptr_t
的prvalue可以转换为
类型的prvalue类型
bool
;结果值为
false

A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a prvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true . A prvalue of type std::nullptr_t can be converted to a prvalue of type bool ; the resulting value is false .

这篇关于我可以使用if(指针)而不是if(pointer!= NULL)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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