Why is the output of the following program showing compile time error?
Please explain "lvalue required"
#include<stdio.h>
int main()
{
int a=5;
printf("%d", ++a++);
return 0;
}
Why is the output of the following program showing compile time error?
Please explain "lvalue required"
#include<stdio.h>
int main()
{
int a=5;
printf("%d", ++a++);
return 0;
}
A language-lawyer proof explanation is a bit lengthy, here's an attempt at a simplified explanation:
The "l" in "lvalue" comes from "left" as in a value that can appear on the left hand side of an assignment operation, which includes many named variables:
int a;
a = 42; // a is an lvalue and can be assigned to
Now due to operator precedence the expression ++a++
is parsed as ++(a++)
. And since a++
modifies a
"later" but, as expression, evaluates to the current value of a
it "returns" a copy of this current value of a
, a temporary value.
This temporary value is unnamed (it is not a
) and it's not an lvalue, wherefore it can't be assigned to.
You can't write a++ = 42
because you'd be assigning to the temporary value, rather than a variable, and for the same reason you can't write ++a++
.
Again, you'll have to dive much deeper, and also give yourself some time to develop an intuitive feeling for what an lvalue is, then this will become much clearer.