+ 1
Why is the output 1 211? Why it is not 1222 ?
2 odpowiedzi
+ 2
The first '1' in output was a boolean true resulted from the evaluation of:
(++x || ++y && ++z)
Here <x> is the only one whose value was altered. Because short circuit evaluation for logical OR only need one true operand to conclude the evaluation result. In this case <x> is considered true because it is non zero. Thus the rest of the operands <y> and <z> are excluded (skipped) from evaluation.
That is also why <x> value was incremented to 2, but <y> and <z> value remains the same (1).
(Edit)
To have all <x>, <y> and <z> value incremented, use logical AND operator rather than logical OR operator, as follows:
(++x && ++y && ++z)
Hth, cmiiw
+ 2
In C++
0 = False
any nonzero integer = True
and
(j>=1 && i<=7 && cond1 && cond2 && ... && condN) // will evaluate until the one condition fails
(j>=1 & i<=7 & cond1 & cond2 & ... & condN) // will evaluate all the conditions
(j>=1 || i<=7 || cond1 || cond2 || ... || condN) // will evaluate until the one condition is true
(j>=1 | i<=7 | cond1 | cond2 | ... | condN) // will evaluate all conditions
So in this line (++x || ++y && ++z)
The compiler will evaluate until the one condition is true and skip the rest of the conditions because it had logical operator || (OR). This is called lazy evaluation.
use | instead. So it will be (++x | ++y && ++z)