+ 26

Can someone explain me why the value of m doesn't change after the second postfix increment operator?

https://code.sololearn.com/c81LHy0m6vXh/?ref=app

11th Jan 2018, 8:32 PM
Robert
Robert - avatar
11 ответов
+ 20
Yes, it's clear, but I'm interested why after the second assignment the value of m (as well the value of x) still doesn't change.
11th Jan 2018, 8:45 PM
Robert
Robert - avatar
+ 19
Oh, excuse me, I meant if it would be written as x = m++. In this case, the same thing is occurred.
11th Jan 2018, 8:54 PM
Robert
Robert - avatar
+ 3
Post fix works only for operations involving '=' sign . For example a++ and ++a will return same value but 1) c=a++ ans c=8 and (2)c=++a ans c=9 will return different value (if a=8)
13th Jan 2018, 4:39 PM
Karthee_aqua
Karthee_aqua - avatar
+ 2
What you need to do is use ++x and ++m instead.
13th Jan 2018, 2:45 AM
Damjan Dimitrov
Damjan Dimitrov - avatar
+ 2
x and m are the same. Thus, m=x++ is the same as m=m++ etc. Because postfix does: 1. store old value 2. increment value 3. return old value the value is internally incremented to 3 but overwritten with 2 again at the end. Self–assignment is useless (wrong) for postfix and prefix operators.
9th Mar 2018, 10:32 PM
K Locher
K Locher - avatar
+ 1
in postfix assignments, first the assign code runs after that the postfix executes. in other words the order of execution of this code is: m = x++; m = x; x = x+1;
11th Jan 2018, 8:42 PM
Mojtaba Kangari
Mojtaba Kangari - avatar
+ 1
In this case x and m are the same variable. When you do m = x++, the value of 2 is stored, then it's incremented by 1, becoming 3. The old value (2) is then assigned to m, also changing x again as they are the same variable.
12th Jan 2018, 12:24 AM
Dennis
Dennis - avatar
+ 1
try using m=x+1
9th Apr 2018, 10:43 AM
DARSH
DARSH - avatar
0
so easy! in second assignment the value of m is 2 and after execution change to 3 and the x value changed to 3. the comment is not correct if you run the code you'll see the result is correct.
11th Jan 2018, 8:50 PM
Mojtaba Kangari
Mojtaba Kangari - avatar
0
int m=2, int& x = m //here m=2 m = x++; // m is assigned 2 and x is incremented to 3 cout<<x<<" "<<m<<endl; x = m++; // here x doesn't becomes 3 because m is 2 and you overwrite the x=3 value with m whose vale is 2 // hope this helps
13th Apr 2018, 10:09 PM
Debabrata Talukdar
Debabrata Talukdar - avatar
0
Look at lesson notes on ++x prefix and x++ postfix the variable in postfix is not updated with new value .until after it is evaluated
23rd Apr 2018, 8:21 PM
Luther Conley