Search code examples
cincrementoperator-precedencepostfix-operator

How to justify C postfix increment operator with precedence table?


I am working with the C operator precedence table to better understand the operator precedence of C. I am having a problem understanding the results of the following code:

int a, b;
a = 1;
b = a++;   // does not seem to follow C operator precedence

Using the precedence table of C operators, I can not explain why with the postfix ++ operator, first the assignment is evaluated and then the increment.

The postfix increment operator (++) has the highest precedence in C and the assignment operator (=) has the lowest precedence. So in the above code first postfix ++ must executed and then assignment =. Therefore both variables a and b should equal 2 but they don't.

Why does the C operator precedence seems not to work with this code?

When doesn't the highest precedence of postfix ++ show itself?


Solution

  • The precedence happens during the parsing. It means that ++ applies to a, not to b = a.

    But ++ means post incrementation, so performed after a is evaluated to be assigned to b

    If you want both to take the value 2 perform a pre-incrementation:

    b = ++a;