Search code examples
c++return-valuepostfix-operatorprefix-operator

How the compiler interprets preincrement/decrement and postincrement/decrement


When someone asks about the difference between post-increment/decrement and pre-increment/decrement, the response is usually that the prefix versions add one to the variable and return the new value of the variable whereas the postfix versions add one to the variable and return the old value.

While messing around, I found out that all of these lines are legal:

int i = 1;
++i;
++++++++++++++i;
(++++++++++++++i)++;
(++++++(++++(++i)))++;
------i;
--++++--++----++i;
i+=++++++++++++++i+i++-i--; 

But none of the following lines are legal:

i++++;
++i++;
--i--;

If I assume that the prefix versions return by reference, this all makes sense (even the last example because postfix has higher precedence than prefix).

Is the assumption/realization that the prefix versions return a reference and the postfix versions return a value correct? Are there any other subtle behavior differences that I don't know about for the pre/post inc/decrement operators?


Solution

  • In C++, the prefix increment/decrement expressions "return" lvalues and the postfix versions return rvalues. In C both forms return rvalues.

    However, be aware that the behavior is undefined if you try to writing to a variable more than once between two sequence points. So the distinction doesn't really matter anyway.