c++nestedternaryassociativity

right associativity and order of execution of nested ternary operator in c++


I have the solution regarding execution order, but I cant understand how right associativity is linked to SCENARIO 2.

a ? b: c ? d : e ? f : g ? h : i // scenario 1 : associativity understood, which is : (a?b:(c?d:(e?f:(g?h:i))))

and

a ? b ? c : d : e // scenario 2 : NOT UNDERSTOOD

From the first answer here, I am able to understand the first scenario but not the second.


Solution

  • The obvious (and generally best) advice about things like this is "just don't do it."

    Other than that, I find the easiest approach to be to think of them like Algol-style ifs. An Algol if was an expression, not a statement, so (much like a conditional, except readable) you could write something like this:

    a = if b then c else d;
    

    The transformation is really pretty simple. x ? is if (x) and : is else. Applying this to a nested conditional is actually pretty easy, and at least in my opinion, the result is much more readable.

    a ? b: c ? d : e ? f : g ? h : i
    

    Transforms to:

    if (a) {
        b; 
    } else if (c) {
        d; 
    } else if (e) {
        f;
    } else if (g) {
        h;
    } else {
        i;
    }
    

    The second is actually just about as easy, as long as you remember that x ? translates directly to if (x). Other than that, we follow the normal C rule that an else matches up with the most recent if that doesn't already have an else associated with it.

    a ? b ? c : d : e
    

    ...becomes:

    if (a) {
        if (b) {
            c;
        }
        else {
            d;
        }
    } else {
        e;
    };