Why isn't "k" incremented in the statement "m = ++i && ++j || ++k" when "++i&&++j" evaluates to true? [duplicate]
Solution 1:
You should avoid coding such unreadable code. It is actually parsed as
m = (++i && ++j) || ++k;
So once j >= 0
the ++j
condition is always true, so ++k
is not evaluated since &&
is a short-cutting and then but ||
is a short-cutting or else (so they may not evaluate their right operand).
So &&
is evaluated as follow: the left operand is evaluated, if it is false it is returned, and then only when it is true (i.e. not equal to 0
) the right operand is evaluated and returned as the evaluated result of the &&
. Likewise ||
is evaluated as follow: the left operand is evaluated. If it is true (non-zero) it becomes the result of the ||
; or else the right operand is evaluated and is the result of the ||
expression.
In particular, when coding if (x > 0 && 20/x < 5)
the division is never attempted for x==0
.
Read also the wikipedia operators in C & C++ & short circuit evaluation & lazy evaluation pages; and please take several hours to read a good C programming book.
Solution 2:
Logical operators have short circuit evaluation, i.e. as soon as a value is determined for the expression, the rest of the expression is not evaluated.
e.g. m = ++i && ++j || ++k;
in this ++i -> true, ++j -> true (non zero value)
hence m = true && true || ++k;
now true && true is true so
m = true || ++k
As in OR operator if 1 side is true, the other is not evaluated so result is true.
Hence k is not incremented.