Search code examples
coperatorspost-incrementpre-increment

Why i+++ works fine but +++i gives error?


I have tried some code in C language but I have encountered this problem.

int i=0;
i=i+++ ++i;   //works fine
//i=i++ +++i;   gives error

My confusion is that how i+++ is running? but +++i return error.


Solution

  • C operators are parsed according to the “longest match” rule. Your first example is parsed as:

    i = i ++ + ++ i ;
    
    i = (i++) + (++i);
    

    Whereas your second example is parsed as:

    i = i ++ ++ + i ;
    
    i = ((i++)++) + i;
    

    The result of the post-increment operator is an rvalue, a copy of the previous value of the variable that was incremented. Applying another post-increment operator to an rvalue is an error because that operator requires an lvalue, intuitively, an expression such as i or *p that can be assigned to.

    Also, this code contains undefined behaviour. You are reading i and modifying it without an intervening sequence point;, &&, ||, ,, or ?:—which means that the program behaviour is unpredictable and will vary across compilers.