Search code examples
cshort-circuiting

Why c is not incremented in the output?


I was working on the Basics of C and was trying to solve the problem below could any one explain why the output of variable c is different?

What is the output of the following program?

int main()
{
   int a = -3, b = 2, c= 0, d;
   d = ++a && ++b || ++c;
   printf ("a = %d,  b = %d, c = %d, d = %d", a, b, c, d);
} 

Ans: -2, 3, 0, 1

Why c is not incremented in the output ?


Solution

  • The variable c is not incremented because the RHS (right-hand side) of an || is not executed unless the LHS evaluates to false, and the LHS evaluates to true. The C || and && operators are 'short-circuit' operators; they do not evaluate the second operand unless the first is insufficient to determine the overall truth of the expression.

    The && binds tighter than the ||, so the operation can be parenthesized as:

    d = (++a && ++b) || ++c;
    

    The value of ++a is -2, which evaluates to true (because any value that is not 0 evaluates to true); the value of ++b is 3, which evaluates to true; so the value of the && term is true. Because true || false and true || true both evaluate to true, there is no need to evaluate the RHS to know the overall result. (The analogous rule for && is that if the first term evaluates to false, there is no need to evaluate the second because the overall expression must be false. If you had a = -1; before the test, then b would not be incremented, because ++a would be zero or false, so the RHS of the && is unevaluated. Of course, then c would be incremented because the LHS of the || would be false, and the RHS would have to be evaluated to determine the overall result.)