Why does c = ++(a+b) give compilation error?
It's just a rule, that's all, and is possibly there to (1) make it easier to write C compilers and (2) nobody has convinced the C standards committee to relax it.
Informally speaking you can only write ++foo
if foo
can appear on the left hand side of an assignment expression like foo = bar
. Since you can't write a + b = bar
, you can't write ++(a + b)
either.
There's no real reason why a + b
couldn't yield a temporary on which ++
can operate, and the result of that is the value of the expression ++(a + b)
.
The C11 standard states in section 6.5.3.1
The operand of the prefix increment or decrement operator shall have atomic, qualified, or unqualified real or pointer type, and shall be a modifiable lvalue
And "modifiable lvalue" is described in section 6.3.2.1 subsection 1
An lvalue is an expression (with an object type other than void) that potentially designates an object; if an lvalue does not designate an object when it is evaluated, the behavior is undefined. When an object is said to have a particular type, the type is specified by the lvalue used to designate the object. A modifiable lvalue is an lvalue that does not have array type, does not have an incomplete type, does not have a const-qualified type, and if it is a structure or union, does not have any member (including, recursively, any member or element of all contained aggregates or unions) with a const-qualified type.
So (a+b)
is not a modifiable lvalue and is therefore not eligible for the prefix increment operator.
You are correct. the ++
tries to assign the new value to the original variable. So ++a
will take the value of a
, adds 1
to it and then assign it back to a
. Since, as you said, (a+b) is a temp value, and not a variable with assigned memory address the assignment can't be performed.