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

后端 未结 4 1540
情书的邮戳
情书的邮戳 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 06:53

    If the pointer is invalid (or rather NULL as pointed out), in the first version short-circuiting will prevent the evaluation of *ptr == value, so the first one is safe.

    The second one will always access *ptr, whether it is valid or not.

提交回复
热议问题