consider this code (C++) :
int x = -4 , y = 5 ;
bool result = x > 0 && y++ < 10 ;
the expression (x > 0) will be evaluated first , and because (x > 0 = false) and due to short-circuit evaluation , the other expression (y++ < 10) won't be evaluated and the value of y will remain 5 .
now consider the following code :
int x = -4 , y = 5 ;
bool result = (x > 0) && (y++ < 10) ;
it is expected that the expressions in parentheses will be evaluated first so that before the logical AND is performed , the expression (y++ < 10) would have been evaluated and the value of y has became 6 , but the reality is that the value of y remains 5 . which means that even with the parentheses the evaluation is short-circuited and the expression (y++ < 10) is ignored .
What is the explanation for this case ?!
The explanation is in the question - short-circuiting.
In C++, evaluation of &&
(and ||
for that matter) is guaranteed to be left-to-right, and as soon as a false
is encountered (respectively true
for ||
), evaluation is guaranteed to stop.
Similar for Java I guess.
The parenthesis are redundant and not relevant in this case - it has nothing to do with operator precedence. It simply has to do with how &&
works:
In fact, the two versions
x > 0 && y++ < 10
(x > 0) && (y++ < 10)
are equivalent, because ++
has the highest precedence, followed by <,>
, and finally &&
. Pedantically, you should have written it as:
(x > 0) && ((y++) < 10)
1 The
&&
operator groups left-to-right. The operands are both implicitly converted to type bool (clause 4). The result is true if both operands aretrue
andfalse
otherwise. Unlike &, && guarantees left-to-right evaluation: the second operand is not evaluated if the first operand isfalse
. (emphasis mine)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With