#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?
#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?
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.
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.