Why isn’t “k” incremented in the statement “m = ++i && ++j || ++k” when “++i&&++j” evaluates to true? [duplicate]

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.

Leave a Comment