0

According to C++, the order of operators is ORDER

I have the following code:

int x = 1, y = 5; 

cout << x * y + ++x * y - x++;

which outputs 13. This means it will evaluate it in this order:

  1. x * y
  2. ++x
  3. (++x * y)
  4. x++
  5. subtraction

But I don't understand why. It does not follow the order of operators.

Wanderer
  • 1,065
  • 5
  • 18
  • 40
  • *But I don't understand why.* It is useful for speed optimizations in a machine code. – 273K Sep 08 '22 at 05:55
  • 2
    See : https://stackoverflow.com/questions/10623114/operation-on-may-be-undefined They said it's UB – Martin Morterol Sep 08 '22 at 06:05
  • 1
    please have a look here: https://stackoverflow.com/questions/949433/why-are-these-constructs-using-pre-and-post-increment-undefined-behavior – Jakob Stark Sep 08 '22 at 06:20
  • 5
    The order of precedence of operators is not the same thing as the order in which the operands are evaluated. The precedence tells you that the expression is the equivalent of `((x * y) + ((++x) * y)) - (x++)`, but it doesn't actually specify in what order `x`, `y`, `++x`, and `x++` are evaluated. There's no "start from the innermost parentheses and work your way out" rule. – Nathan Pierson Sep 08 '22 at 06:22
  • 1
    @NathanPierson the page, that the OP referred to even states that explicitely under [Notes](https://en.cppreference.com/w/cpp/language/operator_precedence#Notes): "Precedence and associativity are compile-time concepts and are independent from order of evaluation, which is a runtime concept." – Jakob Stark Sep 08 '22 at 06:23

0 Answers0