Because the ||
operator operates as a short-circuit if the first operand is true
.
Since the first operand is true
(t == true
), the second condition (that increments i
) is not evaluated.
In the second case, the first operand f
is false
, hence the second operand is evaluated and i
gets incremented by 2
, ending with value 0 + 2 == 2
.
This differs from the &&
operator, which requires both operands to be evaluated.
The bitwise operators &
and |
also evaluate both operands when used in boolean conditions.
Summary
b = (t || ((i++) == 0)); // b = true OR... whatever, just true
b = (t | ((i++) == 0)); // b = true bitwise or 0 == 0 == true (postfix increment, so i gets incremented after evaluation --> true
b = (t | ((++i) == 0)); // b = true bitwise or 0 == 0 == true (prefix increment, so i gets incremented before evaluation --> false
b = (t && ((++i) == 0)); // b = true AND 1 == 0 == false (prefix increment, so i gets incremented before evaluation --> false
b = (t & ((++i) == 0)); // b = true bitwise and 1 == 0 == false (prefix increment, so i gets incremented before evaluation --> false