Search code examples
clogicpre-increment

Why isn't j incremented in (++i || ++j)


I don't understand the output of this code:

 long i=5, j=10;
 if (++i || ++j)  printf("%ld  %ld\n", i, j);
 else  printf("Prog1\n");

The output is 6 and 10. I expected 6 and 11. Why wasn't j incremented?


Solution

  • The logical OR operator || is a short circut operator. That means that the right operand won't be evaluated if the result can be determined by looking only at the left operand.

    Section 6.5.14 of the C standard regarding the Logical OR operator states the following:

    4 Unlike the bitwise | 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 unequal to 0, the second operand is not evaluated.

    In this case, ++i is evaluated and the result is 6 (with the side effect of incrementing i. The logical OR operator evaluates to 1 (i.e. true) if either operand is non zero. Since the left side is non-zero, the right side is not evaluated, and subsequently j is not incremented.