Associativity and execution order are related but not identical.
Associativity exists regardless of any execution - it is defined in mathematics, which consists exclusively of pure functions, so the "order of execution" does not affect the result.
The execution order in the ternary operator in C # is very simple:
- Rate Condition
- Evaluate trueBranch if the condition is true, or falseBranch if the condition is false.
You can imagine associativity rules as "where the partners belong."
Consider this:
a ? b : c ? d : e
If we donโt know anything about how associativity works, we can see different ways of setting parameters:
- (a? b: c)? d: e
- a? b: (c? d: e)
The first approach is left associative, the second is right associative
It is easy to see that both approaches lead to different results. For instance,
(true ? true : false) ? false : false // false true ? true : (false ? false : false) // true
Now, if you rewrite this into separate if (this is usually not the way the Trojan actually executes, but it will do), you will get the following:
if (a) { return b; } else { if (c) return d; else return e; }
The rating is the same as with a simple triple:
- Rate condition
a - If true, evaluate and return
b ; otherwise continue - Rate condition
c - If true, evaluate and return
d ; otherwise rate and return e
This should make it clear how associativity and execution order work. So, we can finish the trip and explain your example.
We have a number of nested conventions:
a ? b ? c ? 0 : 1 : 2 : 3
How is associativity applied here? This is not true. There is no associative operation here! What are you doing:
a ? (b ? (c ? 0 : 1) : 2) : 3
There is no other way to put parens - this is the only possible way to parse statements.
Since the ternary operator, well, the ternary, is a little difficult to understand, but it becomes more obvious when you rewrite it as a function (for example, a โnon-built-in operatorโ):
var f = (a, b, c) => a ? b : c; f(a, f(b, f(c, 0, 1), 2), 3);
There is no ambiguity - there is no alternative way to parse this expression.
The mapping of associativity with binary operators is a bit simpler, so consider this scenario:
a - b - c
If you don't know about associativity - , you can see two alternative ways to set parens - (a - b) - c and a - (b - c) , which can give you two different results. Thus, - not associative.
The comparison with + , which is ("completely") associative - (a + b) + c and a + (b + c) - is exactly the same thing.