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
}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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.)