Brackets and logical operators

consider this code (C ++):

int x = -4 , y = 5 ; bool result = x > 0 && y++ < 10 ; 

first the expression (x> 0) will be evaluated, and therefore (x> 0 = false) and due to the evaluation of the short circuit, the other expression (y ++ <10) will not 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 performing a logical AND, the expression (y ++ <10) would be evaluated, and the value of y would be 6, but the reality is that the value of y will remain equal to 5. which even in parentheses, the evaluation is short-circuited, and the expression (y ++ <10) is ignored.

What is the explanation for this case ?!

+4
source share
3 answers

The explanation in the question is a short circuit .

In C ++, the evaluation of && (and || , for that matter) is guaranteed from left to right, and as soon as it encounters false (correspondingly true for || ), the evaluation is guaranteed to stop.

Sounds like Java, I think.

In this case, the brackets are redundant and irrelevant - this has nothing to do with operator precedence. This is simply related to how && works:

In fact, two versions

 x > 0 && y++ < 10 (x > 0) && (y++ < 10) 

equivalent since ++ has the highest priority, followed by <,> and finally && . Pedantically, you should have written this as:

 (x > 0) && ((y++) < 10) 

5.14 The logical operator AND [expr.log.and]

1 Operators of the && group from left to right. The operands are implicitly converted to type bool (section 4). The result is true if both operands are true and false otherwise. Unlike &, && guarantees an evaluation from left to right: the second operand is not evaluated if the first operand is false . (highlighted by me)

+10
source

When the left side determines the result, the right side is not evaluated.

In the first case, the right side is y++ < 10 , and this is not evaluated. In the second case, the right side (y++ < 10) , and this is not evaluated.

There is no rule in which expressions in parentheses are evaluated first. Brackets are only group operands.

+1
source

Even with parentheses there should still be a short circuit. If you have an expression with pointers:

 int* ptr = 0; int bar = 5; bool result = (ptr != 0) && (*ptr == bar || bar > 10); 

You obviously cannot calmly evaluate the right side of the && there, but the brackets are necessary for priority to work as intended. The brackets simply determine the order of operations that are actually performed, and not that they occur in a specific order.

0
source

Source: https://habr.com/ru/post/1439018/


All Articles