Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not able to understand the working of Pre-increment/ Pre-decrement in C++

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/

like image 508
Sohil Grandhi Avatar asked Dec 31 '25 10:12

Sohil Grandhi


2 Answers

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.

like image 127
Some programmer dude Avatar answered Jan 06 '26 13:01

Some programmer dude


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

like image 39
CIsForCookies Avatar answered Jan 06 '26 14:01

CIsForCookies



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!