检查指针是否为空是否安全,然后在相同的if语句中取消引用它是否安全? [英] Is it safe to check if a pointer is null, then dereference it in the same if statement?

查看:90
本文介绍了检查指针是否为空是否安全,然后在相同的if语句中取消引用它是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果传入空指针,以下代码是否安全?

Is the following code safe if a null pointer is passed in?

if(ptr && *ptr == value)
{
   //do something
}

检查的顺序重要吗?如果我将其更改为此可以正常工作吗?

Does the order of the checks matter? Does it work if I change it to this?

if(*ptr == value && ptr)
{
   //do something
}

推荐答案

前者是正确和安全的,后者则不是.

The former is correct and safe, the latter is not.

内置的&&运算符具有短路语义,这意味着当且仅当第一个为true时,才对第二个参数求值.

The built-in && operator has short-circuit semantics, meaning that the second argument is evaluated if and only if the first one is true.

(超载运算符不是这种情况.)

(This is not the case for overloaded operators.)

这篇关于检查指针是否为空是否安全,然后在相同的if语句中取消引用它是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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