+ 1

Operator precedence vs short circuit evaluation

In the following code (created by Nikhil Dahma) #include <iostream> using namespace std; int main() { int x=1,y=1,z=1; cout << (++x || ++y && ++z); cout << x << y << z; return 0; } Even though && has higher precedence than ||, short circuit evaluation seems to override that, but why?

20th Jun 2022, 7:58 PM
Edward Finkelstein
Edward Finkelstein - avatar
2 Antworten
+ 5
operator precedence has absolutely nothing to do with order of evaluation. operator precedence dictates the grouping between operators and their operands (i.e. operator precedence says which operand belongs to which operator). so, operator precedence rules tell you that the grouping should be: ( ++x ) || ( ++y && ++z ); then the expression as a whole evaluates the left-hand-side of the ||, with the side-effect of incrementing "x", which evaluates to true. that means that the right-hand-side of the || (the && expression) is not evaluated at all because it is not needed to determine the truth of the overall expression. for example : If you have i + j * k, where "*" has a higher precedence than "+", then it is evaluated as i + (j * k), is it not? change + to || and * to && and the expressions are isomorphic and the interpretation is similar. the big difference between the arithmetic expression and the logical expression is that the operands of the logical expression have to be evaluated left-to-right but the operands of the arithmetic expression do not; the compiler could evaluate (j * k) before evaluating (i) (but must evaluate (j * k) before doing the addition). by contrast, in the logical expression (i || j && k), the compiler must evaluate (i) before evaluating (j && k), and when (i) turns out to be true, it must not evaluate either (j) or (k).
20th Jun 2022, 9:08 PM
MO ELomari
MO ELomari - avatar
+ 1
Mohamed ELomari that makes a lot of sense, thanks
21st Jun 2022, 6:19 AM
Edward Finkelstein
Edward Finkelstein - avatar