Search code examples
clogical-operatorspost-incrementlogical-orlogical-and

Evaluate Postfix and Logical Operators in C with no short-circuiting approach


I came across this question when studying logical operators and conditionals in C.

#include <stdio.h>
int main() {

    int x = 3;
    int y = 2;
    int z = 3;
    printf("Result #4 = %d\n", x++ <= 3 || y++ >= 2 && z++ != 3);
    printf("x: %d y: %d z: %d\n", x, y, z);
    return 0;

}

Output:

Result #4 = 1
x: 4 y: 2 z: 3

I do not understand the last line of output. The values for x, y, z do not match my understanding.

Here is my line of thought.

  • The expression x++ <= 3 || y++ >= 2 && z++ != 3 will be evaluated like : x++ <= 3 || (y++ >= 2 && z++ != 3).
  • Then, y++ >= 2 will be true and y value will be incremented to 3.
  • Then, z++ != 3 will be false and z value will be incremented to 4.
  • Since the whole condition is false, the RHS of the OR conditional will be evaluated.
  • So, x++ <= 3 will be evaluated to true and x will be incremented to 4.
  • The whole condition will be true since x++ <= 3 will be evaluated as true.

I tried to find the reference textbook or worksheet from which this question was taken, but I was not able to. I did some research on StackOverflow and I don't think this is a short-circuited condition. If it were, I don't understand why.

The only explanation I can come up with is that the x value will have the side effect implemented (x incremented) because it is evaluated as true, while the rest of the OR statement will not have its side effects since it is evaluated as false, therefore y and z will not be incremented. Is this the case?


Solution

  • The expression x++ <= 3 || y++ >= 2 && z++ != 3 will be evaluated like : x++ <= 3 || (y++ >= 2 && z++ != 3).

    If you think in terms of parentheses then why do you apply them at the right side only and not at the other side? The expression would be rather evaluated like (x++ <= 3) || (y++ >= 2 && z++ != 3).

    Why do you assume that the right side is evaluated first? Equal parts are evaluated through left to right.

    int x = 3 and x++ <= 3 is evaluated first: 3 <= 3 is true and x gets 4. The right side is not evaluated, y and z keep their initial values.