#include <stdio.h>
int main () {
int x, y, z;
x = y = z = 1;
++x || ++y && ++z;
printf ("x = %d\t y = %d\tz = %d\n", x, y, z);
//op : x = 2 y = 1 z = 1
//why is 'x' only incrementd?
x = y = z = -1;
++x || ++y && ++z;
printf ("x = %d\t y = %d\tz = %d\n", x, y, z);
//op : x = 0 y = 0 z = -1
//why are 'x' and 'y' incremented?
x = y = z = 1;
++x && ++y || ++z;
printf ("x = %d\t y = %d\tz = %d\n", x, y, z);
//op : x = 2 y = 2 z = 1
//why is 'x' only incrementd?
x = y = z = -1;
++x && ++y || ++z;
printf ("x = %d\t y = %d\tz = %d\n", x, y, z);
//op : x = 0 y = -1 z = 0
//why are 'x' and 'z' incremented?
//Does this incrementation depend on the value stored in the variable?
}
The reason is that &&
and ||
short circuit.
That is, once they know what the end result of the boolean expression will be, they stop evaluating.
So, if you do 1 || x++
, then x
will never be incremented, because any non-zero boolean value is a true value.
Likewise, if you do 0 && x++
, x++
never will get executed either.
See also:
|| and && short-circuit. What that means is that they perform as little work as possible to return their value, only executing the right side if the left side doesn't nail the answer.
For instance:
1 || anything();
In this case, anything() will never execute, because || can simply return as soon as it evaluates the 1; no matter what anything()'s return value, the return value of || in this expression can never be 0.
Similarly:
0 && anything_else();
Here, anything_else() will never execute, because && already knows that its value can never be anything but 0.
In your examples, the ++ preincrements don't actually affect the short-circuiting, except to hide the values that the boolean short-circuit operators are actually making their decisions on.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With