-2
#include <stdio.h>

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

Here value of c should increase to 1 but it is giving 0, why?

Cœur
  • 37,241
  • 25
  • 195
  • 267
  • 1
    [(Boolean) Short-Circuit Evaluation](https://en.wikipedia.org/wiki/Short-circuit_evaluation) strikes again. – alk Oct 13 '17 at 14:29
  • I can only guess it's because of the `||` operator which doesn't execute since the first part `&&` is already `true` so the value of `|| ++c` doesn't matter. – anteAdamovic Oct 13 '17 at 14:31
  • @AnteJablanAdamović Why guess? – Eugene Sh. Oct 13 '17 at 14:31
  • @EugeneSh Because I'm unsure of how it works myself, just using the logic and knowledge of what I know. – anteAdamovic Oct 13 '17 at 14:32
  • 1
    @AnteJablanAdamović Take a look at the standard: http://port70.net/~nsz/c/c11/n1570.html#6.5.13p4 and you won't have to guess anymore :) – Eugene Sh. Oct 13 '17 at 14:34

2 Answers2

4

It's because of short-circuiting. If you have a && b, then b will only be evaluated if a is true. Similarly, if you have a || b, then b will only be evaluated if a is false.

In your case, ++a && ++b || ++c groups as (++a && ++b) || ++c. First ++a is evaluated, and it's true, so ++b is evaluated, and it's also true. At this point, evaluation stops because it is now certain that the result of the || operator is true, so ++c is never evaluated.

Tom Karzes
  • 22,815
  • 2
  • 22
  • 41
2

Because the || doesn't evaluate the right hand side if the left hand side evaluated to true. In your example,

++a && ++b

evaluates to non-zero, which is treated as a true. Therefore, according to the rules of lazy evaluation, the ++c is completely ignored.

Steve
  • 1,747
  • 10
  • 18