Operator associativity

Updated: 11/12/2023 by Computer Hope
'1+1=2 ' written on a chalkboard.

Operator associativity refers to the order operators of the same precedence are evaluated in an expression. Essentially, it's a rule that tells us whether we go from left to right or right to left when dealing with operators of the same priority.

Operator associativity is useful because it ensures that mathematical operations are carried out correctly in the absence of parentheses. The associativity is often predetermined for specific operators in programming languages to avoid ambiguity and ensure consistent evaluation order.

Operator associativity example

For example, let's use the expression a - b + c. If the operator is left-associative, it is evaluated from left to right. So, the expression is effectively treated as (a - b) + c. On the other hand, if the operator were right-associative, the expression would be evaluated from right to left: a - (b + c). If we fill in the expression with the numbers eight, three, and two, you can see that the results differ based on grouping: (8 - 3) + 2 = 7 and 8 - (3 + 2) = 3.

Eval, Programming terms