C Sharp

Left and Right Associativity

Associativity determines which side of an expression should be evaluated first. As an example, the following expression could result in a sum of either 21 or 33 depending on the left or right associativity of the - operator: -

42-15-6

The - operator is defined as left-associative, meaning that 42-15 is evaluated and then 6 is subtracted from the result. If the - operator were defined as right-associative, the expression to the right of the operator would be evaluated first: 15-6 would be evaluated and then subtracted from 42.

All binary operators-that is, operators that take two operands-except the assignment operators, are said to be left-associative, meaning that the expression is evaluated from left to right. Therefore, a + b + c is the same as (a + b) + c where a + b is evaluated first and c is added to the resulting sum. Assignment operators and the conditional operator are said to be right-associative-the expression is evaluated from right to left. In other words, a = b = c is equivalent to a = (b = c). This trips up some people who want to place multiple assignment operations on the same line, so let's look at some code: -

using System;
class RightAssocApp
{
    public static void Main()
    {
        int a = 1;
        int b = 2;
        int c = 3;
        Console.WriteLine("a={0} b={1} c={2}", a, b, c);
        a = b = c;
        Console.WriteLine("After 'a=b=c': a={0} b={1} c={2}", a, b, c);
    }
}

The results of running this example are the following: -

a=1 b=2 c=3
After 'a=b=c': a=3 b=3 c=3

Seeing an expression evaluated from the right might be confusing at first, but think of it like this: If the assignment operator were left-associative, the compiler would first evaluate a = b, which would give a value of 2 to a, and then it would evaluate b = c, which would give a value of 3 to b. The end result would be a=2 b=3 c=3. Needless to say, that wouldn't be the expected result for a = b = c, and this is why the assignment and conditional operator are both right-associative.

by BrainBellupdated
Advertisement: