+ 26
Can someone explain me why the value of m doesn't change after the second postfix increment operator?
11 Respuestas
+ 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.
+ 19
Oh, excuse me, I meant if it would be written as x = m++. In this case, the same thing is occurred.
+ 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)
+ 2
What you need to do is use ++x and ++m instead.
+ 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.
+ 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;
+ 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.
+ 1
try using m=x+1
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.
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
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