1
int x = 10, y = 20, z = 10;
if (x == 10 || y == 20 && (z = 50))
    printf("%d", z);

I expected the value of z in output to be 50, but it is 10. If && has higher precedence, why is z not assigned to 50?

  • 2
    [What is short-circuit evaluation in C?](https://stackoverflow.com/questions/45848858/what-is-short-circuit-evaluation-in-c) This should really have been taught by any decent book, course or tutorial. – Some programmer dude Jun 16 '23 at 13:26
  • Also related: [Operator precedence and associativity](https://en.cppreference.com/w/c/language/operator_precedence). – Some programmer dude Jun 16 '23 at 13:28
  • 1
    Since `x == 10` is true, evaluation of the expression stops at that point. This is guaranteed by the C language. Read about the `&&` and `||` operators. – Tom Karzes Jun 16 '23 at 13:42

1 Answers1

3

If the left operand for || is truthy, the RHS is not evaluated. So, the assignment to z never happens, and the initialised value remains.

This is called Short-circuit evaluation

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261