associativity

What is associativity of operators and why is it important?


What is associativity for an operator and why is it important?


Solution

  • 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