Home > Net >  Precedence between multiple different operators Order of evaluation
Precedence between multiple different operators Order of evaluation

Time:09-18

I have some problems with how an expression Order of evaluation is executed.

    int x = 1;
    int y = 2;

    int z =   x || y  ; // how this expression actually executed?

    cout << x << " " << y << " " << z;

output: 2 2 1

I know if started from left to right with x it was evaluated and a short circuit will be done.

But why we didn't evaluate from y which has higher precedence than any other operator here and then do x which has less precedence and finally do || between them?

CodePudding user response:

Order of evaluation and operator precedence are not the same thing.

Operator precedence here tells us that the expression x || y is equivalent to ( x) || (y ) rather than some other placement of parentheses, but that still doesn't tell us in which order the subexpressions are evaluated and operator precedence is not relevant for that (aside from the grouping of expressions).

By-default there are no guarantees for this ordering in C . It is not guaranteed to be left-to-right and evaluations of different branches of the expression tree can interleave. The value computations and side effects of subexpressions are said to be unsequenced.

However some expressions enforce some sequencing rules. In particular the built-in || and && are special in that they will conditionally evaluate only their left-hand operand at all.

|| will always sequence the value computation and all side effects of the left-hand side before those of the right-hand operand (if it is evaluated at all). And if the left-hand operand's value is true it will not evaluate the right-hand operand. This is known as short-circuit evaluation. What operators are used in the expressions in the left- and right-hand operands is irrelevant.

So x is evaluated first, resulting in a value 2 which converted to bool is true. Therefore y is never evaluated. Whether or not the pre-increment or post-increment has higher operator precedence is completely irrelevant at this stage.

  •  Tags:  
  • c
  • Related