Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parentheses and logical operators

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 ?!

like image 514
m0stafa Avatar asked Dec 21 '22 15:12

m0stafa


1 Answers

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)

5.14 Logical AND operator [expr.log.and]

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 are true and false otherwise. Unlike &, && guarantees left-to-right evaluation: the second operand is not evaluated if the first operand is false. (emphasis mine)

like image 142
Luchian Grigore Avatar answered Dec 24 '22 01:12

Luchian Grigore