Can someone please explain what is happening in the following code? (Taken from GeeksForGeeks)
int main(){
int a = 10;
++a = 20; // works
printf("a = %d", a);
getchar();
return 0;
}
What exactly is happening when the statement ++a = 20 is executed? Also, please clarify why this code fails in execution?
int main(){
int a = 10;
a++ = 20; // error
printf("a = %d", a);
getchar();
return 0;
}
Code Taken From: http://www.geeksforgeeks.org/g-fact-40/
When you do
++a = 20;
it's roughly equivalent to
a = a + 1;
a = 20;
But when you do
a++ = 20;
it's roughly equivalent to
int temp = a;
a = a + 1;
temp = 20;
But the variable temp doesn't really exist. The result of a++ is something called an rvalue and those can't be assigned to. Rvalues are supposed to be on the right hand side of an assignment, not left hand side. (That's basically what the l and r in lvalue and rvalue comes from.)
See e.g. this values category reference for more information about lvalues and rvalues.
This is the difference between r and l values. If you would have compiled the 2nd code snippet with gcc you would have seen this:
lvalue required as left operand of assignment
meaning, that a++ is rvalue and not a lvalue as it should be if you want to assign something to it
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With