c++right-to-leftconditional-operatorassociativityleft-to-right

How does associativity of operator work during evaluation of expression?


I was learning precedence rule in C++. In which conditional operator is said to have Right to Left associativity. I interpret this as evaluation of expression start from right and proceed to left. So, for the below code-

int a=1, b=2, c;
c=a>b? a=a*2: a=a+3;
cout<<c<<" "<<a;

I assume output as

8 8

But actual output is

4 4

I don't understand how actually this associativity works, because from the above output it seems to me conditional operator have left to right associativity.


Solution

  • Associativity tells you what happens if you have multiple instances of the same operator in a row. For example,

    f() - g() - h()
    

    parses as

    (f() - g()) - h()
    

    and not

    f() - (g() - h())
    

    because - is left associative, not right associative.

    None of this has anything to do with evaluation order, which determines which function is called first.

    As for ?: being right associative, it means

    a ? b : c ? d : e
    

    parses as

    a ? b : (c ? d : e)
    

    (This makes slightly more sense if you think of ?...: as a single operator.)

    However, ?: guarantees left-to-right evaluation: The first operand is always evaluated first, then exactly one of the other operands (depending on the truth value of the first result).


    In your example,

    c=a>b? a=a*2: a=a+3
    

    (please never put assignments inside ?: like that in real code) is parsed as

    c = ((a>b) ? (a=a*2) : (a=a+3))
    

    This is entirely due to precedence, not associativity (we don't have multiple identical operators next to each other here).

    a>b is evaluated first (yielding false), which causes a=a+3 to be evaluated (yielding 4), which is then assigned to c.