Search code examples
c++c++14operators

what is the difference between operators associativity and order of evaluation in c++


What is the difference between operators associativity and order of evaluation?

I have expected that operator associativity is a precedence of operators which in the same group and have the same precedence, but I cannot understand the difference between operators associativity and order of evaluation


Solution

  • Associativity informs the order of evaluation of the components of an expression, but it does not entirely define it.

    Consider this expression: a + b + c. Associativity of + is left-to-right, so we know that this is conceptually equivalent to ((a + b) + c). What this means is that the expression a + b gets evaluated before the addition of that result to c. That informs the order of evaluation.

    But this does not entirely define ordering. That it, it does not mean that a or b gets evaluated before c. It is entirely possible for a compiler to evaluate c first, then a and then b, then +ing a and b, and finally +ing that to the result of c. Indeed, in C++14, it is possible for a compiler to partially evaluate c, then evaluate part of a, then some of b, then some of c etc. That all depends on how complex a, b, and c are.

    This is particularly important if one of these is a function call: a(x + y, z) + b + c. The compiler can evaluate x, then c, then z, then y, then b, then x + y, then evaluate a, then call the result of that evaluation, then adding that to b, then adding that to c.