What is associativity of operators and why is it important?
For operators, associativity means that when the same operator appears in a row, then which operator occurence we apply first. In the following, let Q
be the operator
a Q b Q c
If Q
is left associative, then it evaluates as
(a Q b) Q c
And if it is right associative, then it evaluates as
a Q (b Q c)
It's important, since it changes the meaning of an expression. Consider the division operator with integer arithmetic, which is left associative
4 / 2 / 3 <=> (4 / 2) / 3 <=> 2 / 3 = 0
If it were right associative, it would evaluate to an undefined expression, since you would divide by zero
4 / 2 / 3 <=> 4 / (2 / 3) <=> 4 / 0 = undefined
Simple!!
Left Associative means we evaluate our expression from left to right
Right Associative means we evaluate our expression from right to left
We know *, /, and % have same precedence, but as per associativity, answer may change:
For eg: We have expression: 4 * 8 / 2 % 5
Left associative: (4 * 8) / 2 % 5 ==> (32 / 2) % 5 ==> 16 % 5 ==> 1
Right associative: 4 * 8 /(2 % 5) ==> 4 * ( 8 / 2) ==> 4 * 4 ==> 16
it is the order of evaluate for operators of the same precedence. The LEFT TO RIGHT or RIGHT TO LEFT order matters. For
3 - 2 - 1
if it is LEFT to RIGHT, then it is
(3 - 2) - 1
and is 0. If it is RIGHT to LEFT, then it is
3 - (2 - 1)
and it is 2. In most languages, we say that the minus operator has a LEFT TO RIGHT associativity.
Update 2020:
The situation about 3 - 2 - 1
might seem trivial, if the claim is, "of course we do it from left to right". But in other cases, such as if done in Ruby or in NodeJS:
$ irb
2.6.3 :001 > 2 ** 3 ** 2
=> 512
The **
is "to the power of" operator. The associativity is from right to left. And it is
2 ** (3 ** 2)
which is 2 ** 9
, i.e., 512
, instead of
(2 ** 3) ** 2
which is 8 ** 2
, i.e., 64
.
There are three kinds of associativity:
The Associative property in mathematics
Order of Operations in programming languages
Associativity in CPU caches.
The Associative property in mathematics is a property of operators such as addition (+). This property allows you to rearrange parentheses without changing the value of a statement, i.e.:
(a + b) + c = a + (b + c)
In programming languages, the associativity (or fixity) of an operator is a property that determines how operators of the same precedence are grouped in the absence of parentheses; i.e. in what order each operator is evaluated. This can differ between programming languages.
In CPU caches, associativity is a method of optimizing performance.