Reputation: 1277
I was curious and find out the current piece of code does not work however I can not figure out why:
#include <stdio.h>
void main(){
int a = 42;
printf("%d\n", ++a++);
}
It does not seem like a wrong syntax to me. Could somebody explain the error output?
first.c: In function ‘main’:
first.c:5:17: error: lvalue required as increment operand
printf("%d\n", ++a++);
Upvotes: 0
Views: 7969
Reputation: 535
In C, ++x
is a value, not an lvalue. Its effect is to increment x
, and evaluate to the newly assigned value of x
. Since ++x
is not an lvalue, it cannot be incremented.
In C++, ++x
is an lvalue, not an rvalue. Its effect is to increment x
, and evaluate to x
as an lvalue. Since ++x is an lvalue again, it can be incremented again.
The reason why it makes sense for ++x
to be an lvalue in C++ is because C++ introduced reference types. Given
void f(int &);
int i;
it may make sense to call f(++i)
, which passes i by reference after incrementing it.
Since C doesn't have reference types, there's little point in ++i being an lvalue. Historically, it never was, and unlike C++, C never gained a compelling reason to change the rules.
Note that C++ required more extensive changes than making ++x
an lvalue to actually let it work. Making ++x
an lvalue, without anything else, would make ++x undefined behavior because there would not be a sequence point between the modification to x and the subsequent lvalue-to-value conversion. Even more clearly so for ++++x
. C++ had to modify the sequencing rules to make it work. In C, modifications to the sequencing rules might cause problems for existing compilers to conform to the new rules, so such modifications would likely be rejected unless there's a big benefit.
Upvotes: 5
Reputation: 409166
++a++
is equal to ++(a++)
(because of operator precedence), and the value returned by a++
is a non-lvalue object expression (also known as rvalues).
Such values are (in essence) ephemeral and can not be modified by the prefix ++
operator.
Upvotes: 16
Reputation: 20901
Could somebody explain the error output?
It means C doesn't support such an operation.
Upvotes: 2