Consider the following C code:
#include <stdio.h>
int main(void) {
int a = 0;
printf("%d\n", ++a += 1);
}
++ has precedence over += so it should be evaluated first. So we have a on the left and 1 on the right. Now based on my understanding ++a should result in a (only changes its value) which is lvalue so why this statement gives the following error:
lvalue required as left operand of assignment
>Solution :
The prefix increment operator ++ results in the incremented value of its operand, however it is not an lvalue. Section 6.5.3.1p2 of the C standard: describes the semantics as follows:
The value of the operand of the prefix
++operator is incremented.
The result is the new value of the operand after incrementation. The
expression++Eis equivalent to(E+=1). See the discussions of
additive operators and compound assignment for information on
constraints, types, side effects, and conversions and the effects of
operations on pointers.
Then section 6.5.16.2p3 regarding compound assignment operators states:
A compound assignment of the form
E1 op = E2is equivalent to the
simple assignment expressionE1 = E1 op (E2), except that the lvalue
E1is evaluated only once, and with respect to an
indeterminately-sequenced function call, the operation of a compound
assignment is a single evaluation.
And 6.5.16p3 regarding the assignment operator further states:
An assignment operator stores a value in the object designated by the
left operand. An assignment expression has the value of the left
operand after the assignment, but is not an lvalue.
So it is explicitly not allowed. Even if it was, an expression such as ++a += 1 would cause a to be modified more than once without an intervening sequence point which would trigger undefined behavior.
This is one of those place where C and C++ differ. C++ does in fact allow the result of the = operator, and by extension compound assingment and prefix ++/--, to be an lvalue.