Search code examples
csequence-pointsassociativity

Associativity and Sequence Points in C


Since the associativity of '?' is from right to left,any 2 consecutive '?' operators must be treated as such,Right?

Now,

int x=-1;
int y=x?x++?x:-1:1;

I expect this to be executed as:

int y = x ? (x++?x:-1) : 1;

Now since its being executed from right to left,when encountering the first '?' in the statement,x's value is 0 and the expression is as

int y= x? 0 : 1;

hence i expected y to be 1,but it shows Zero on my dev-cpp.Where am i wrong?


Solution

  • You have the order of evaluation wrong. In a ? b : c, a is always evaluated first, then either b or c is evaluated.

    I've marked up your example so that I can identify subexpressions:

                c
    int y=x?x++?x:-1:1;
          a bbbbbbbb
    

    (a) is evaluated, yielding -1, so (b) is evaluated. There, x++ is evaluated, yielding -1 again, so (c) is evaluated. At this point, x is 0.

    Or, with more verbose, clearer code, it's as if you said:

    int x = -1;
    int y;
    if (x != 0)
    {
        int new_x = x + 1;
        if (x != 0)
        {
            y = new_x;
        }
        else
        {
            y = -1;
        }
    }
    else
    {
        y = 1;
    }