Search code examples
c++incrementprefixdecrementpostfix-operator

Why does C++ accept multiple prefixes but not postfixes for a variable


While looking into Can you have a incrementor and a decrementor on the same variable in the same statement in c

I discovered that you can have several prefix increment/decrement operators on a single variable, but only one postfix

ex:

++--++foo; // valid
foo++--++; // invalid
--foo++;   // invalid

Why is this?


Solution

  • This is due to the fact that in C++ (but not C), the result of ++x is a lValue, meaning it is assignable, and thus chain-able.

    However, the result of x++ is NOT an lValue, instead it is a prValue, meaning it cannot be assigned to, and thus cannot be chained.