Both || and && force left to right operation. Both fully evaluate their LHS operand and apply any side effects before evaluating the RHS. Both short-circuit; if the result of the expression can be determined from the LHS, the RHS is not evaluated at all.
For ||, if the LHS evaluates to a non-zero value, then the RHS is not evaluated (true OR x is always true).
For &&, if the LHS evaluates to a zero value, then the RHS is not evaluated (false AND x is always false).
&& has higher precedence than ||, which has higher precedence than assignment, so the expression is parsed as
m = (++i || (++j && ++k ))
and evaluated as follows:
++iis evaluated first (||forces left-to-right evaluation) and the side effect of incrementingiis applied;- Since
iis initially-3,++ievaluates to-2; - Since
++ievaluates to a non-zero value, the RHS expression++j && ++kis not evaluated at all1; - The result of an operation involving
||or&&is a boolean value (either0or1) – since++iis non-zero,++i || ++j && ++kevaluates to 1; 1is assigned tom.
So, by the time all of this is done, the following are true:
i == -2
j == 2 // unchanged
k == 0 // unchanged
m == 1
1. If ++i had evaluated to 0, then ++j && ++k would have been evaluated by evaluating ++j first, and if the result was non-zero, evaluating ++k.
solved How to solve this logical expression? [closed]