-3
int x=0, y=0, z=0;
z = (x==1) && (y=2);
printf("%d ", y);

I'm wondering the output is 0. Why the output is not 2?

dwbFrank
  • 115
  • 1
  • 5
  • 3
    Learn about [*short-circuit evaluation*](https://en.wikipedia.org/wiki/Short-circuit_evaluation). – Some programmer dude Dec 18 '17 at 14:16
  • 2
    Why do you think it *should* be 2? – Scott Hunter Dec 18 '17 at 14:16
  • 1
    Basic property, RHS is evaluated only if LHS is TRUE, – Sourav Ghosh Dec 18 '17 at 14:16
  • 1
    `x==1` is 0(False), so what happens after `&&` is not evaluated. – harmands Dec 18 '17 at 14:17
  • other dupes: [Short-circuit evaluation on C](https://stackoverflow.com/questions/45848858/short-circuit-evaluation-on-c) / [Short circuit evaluation and side effects](https://stackoverflow.com/questions/3635722/short-circuit-evaluation-and-side-effects) – underscore_d Dec 18 '17 at 14:17
  • Why so much DV ? – Stargateur Dec 18 '17 at 14:18
  • 2
    When `(x==1) && (y=2)` is computed, as `(x==1)` is false, it stops calculation, and `(y=2)` is never called. – Nayfe Dec 18 '17 at 14:18
  • 1
    @Stargateur: Multiply-duplicated question showing no effort to solve it, I would guess. – Scott Hunter Dec 18 '17 at 14:20
  • 1
    First of all you are printing the value of y which was initialized as 0. Thus it printed 0. Considering as it was your fault and you wanted to print the value of z. Now in z, x==1 is false as it was 0 and as soon as it got false it stopped evaluating the next sequence of code. This how logical AND behaves unlike logical OR. Finally you got 0 as result. – Suvam Roy Dec 18 '17 at 14:26

1 Answers1

1

Because of how C deals with the logical operators:

Since x==1 returns "false", there is no need to check the RHS in order to conclude that the end result of the operator && is false. Hence, RHS is not evaluated and y stays at its previous value.