Is it safe to check if a pointer is null, then dereference it in the same if statement?

后端 未结 4 1632
情书的邮戳
情书的邮戳 2021-02-20 06:43

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

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

Does the order of the checks

4条回答
  •  庸人自扰
    2021-02-20 07:04

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

    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.)

提交回复
热议问题