1

I have written this simple C code,

int main()
{
        int *p = NULL;
        if (p && *p);
        //if (*p && p);
        return 0;
}

When I run this code, unexpectedly I didn't any seg fault. But if I change order of p and *p in if ()(like in the comment) I do get seg fault.

Can someone explain why?

1
  • The first is a standard ideom. You would have found out yourself if you had done a little research. Or if you just had read the description of the && operator. But apparently first asking is easier than learning. Re. the 2nd variant (*p %% p): why do you expect a segfault? You invoke undefined behaviour; think about the meaning of the word undefined. Commented Aug 7, 2016 at 13:26

1 Answer 1

4

The && operator has short-circuit evaluation. If the result can be determined by just looking at the value of the left operand, then the right operand is not evaluated. For the && operator, this means that if the left side evaluates to false, it doesn't evaluate the right side, and the result is false. In other words,

if (p && *p) ...

is equivalent to

if (p) if (*p) ...

From the C11 standard, section 6.5.13/4:

Unlike the bitwise binary & operator, the && operator guarantees left-to-right evaluation; if the second operand is evaluated, there is a sequence point between the evaluations of the first and second operands. If the first operand compares equal to 0, the second operand is not evaluated.

Sign up to request clarification or add additional context in comments.

7 Comments

any reference to your answer?
@ParthaBera: Added.
this applies to c also?
@ParthaBera yes it does apply to C also
@ParthaBera: Sorry, I didn't notice the C tag. I've changed my answer to use the equivalent reference from the C11 standard.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.