Question

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?

Was it helpful?

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.

OTHER TIPS

In C++ language prefix increment/decrement operators return lvalues, while postfix ones return rvalues. Meanwhile, all modifying operators require lvalue arguments. This means that the result of prefix increment/decrement can be passed on to any other additional operator that requires an lvalue argument (including additional increments/decrements).

For the very same reason in C++ you can write code like this

int i = 0;
int *p = &++i;

which will increment i and make p point to i. Unary & requires lvalue operand, which is why it will work with the result of prefix ++ (but not with postfix one).

Expressions with multiple built-in prefix increments/decrements applied to the same object produce undefined behavior, but they are nevertheless well-formed (i.e. "compilable").

Expressions like ++foo-- are invalid because in C++ postfix operators have higher precedence than prefix ones. Braces can change that. For example, (++foo)-- is a well-formed expression, albeit leading to undefined behavior again.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top