cshort-circuit-evaluation

How do short circuit operators decide how the statement is interpreted?


I have just learned about short circuit operators in C that if the result can be deduced from the left statement the right statement is not run. However, if there are more than one of these operators, what decides which statement is part of which? Such as the code below, if according to operator precendence && is higher than || that wouldn't the left part be (a+b)%d while d++||c++ be the other part? Because if I ran the program and checked the values of d and c after, the value of d is not incremented while c is, which means c++ was done? Why does this happen?

int main()
{
    int a=5,b=8,c=0,d=1;
    printf("%d\n",(a+b)%d&&d++||c++);
    printf("%d %d",c,d);
    return 0;
}

Solution

  • && does indeed have a higher precedence over ||, meaning that && will be evaluated first.

    However, the result of (a+b)%d is going to be 0. Because the division rest between 13 and 1 is 0, which evaluates in C as false. In this case, the right operand of the && (the d++) will no longer be executed.

    || is then going to be evaluated. The left operand will have a result of 0, meaning that c++ (the right operand) also needs to be evaluated. And this is why it is incremented.