Home > Enterprise >  what is the difference between operators associativity and order of evaluation in c
what is the difference between operators associativity and order of evaluation in c

Time:02-02

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

CodePudding user response:

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.

CodePudding user response:

In C , "associativity" refers to the direction in which an operator is applied to its operands, while "order of evaluation" refers to the order in which operands are evaluated. For example, the addition operator ( ) has left-to-right associativity, meaning multiple additions in an expression are evaluated from left to right. However, the order of evaluation is not guaranteed to be predictable, and can affect the result of an expression with side effects. Understanding these concepts is important for writing correct and predictable code.

  • Related