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:
++i
is evaluated first (||
forces left-to-right evaluation) and the side effect of incrementingi
is applied;- Since
i
is initially-3
,++i
evaluates to-2
; - Since
++i
evaluates to a non-zero value, the RHS expression++j && ++k
is not evaluated at all1; - The result of an operation involving
||
or&&
is a boolean value (either0
or1
) – since++i
is non-zero,++i || ++j && ++k
evaluates to 1; 1
is 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]