+ 1

Why b=b++ does not change b value?

int b=1; b=b++; cout<<b; Result will be 1. Why b !=2 ? int x=b++; cout<<endl<<b; Result will be 2

8th Nov 2016, 9:38 PM
Юрий Алчинов
Юрий Алчинов - avatar
4 Réponses
+ 6
because it first store b in b variable then add 1. You should do b = ++b; in order to add 1 to b then store it on b.
8th Nov 2016, 9:57 PM
Marco Capo
Marco Capo - avatar
+ 1
Thanks for the reply, but I know how ++b works. I'm interested in b=b++ I think it works like that 1) b value pushed to stack 2) b value incremented by 1 3) old b value poped from stack into b. That is why b is still the same. Other words, It is similar to int temp = b; b++; b=temp;
8th Nov 2016, 10:02 PM
Юрий Алчинов
Юрий Алчинов - avatar
+ 1
Typically post increment is implemented as : int post++(int &i) { int temp = *i; *i = *i + 1; return temp; } We can observe here that when we use b= b++ then first the value of b is incremented at the original location and returns the previous value of b, so it becomes b= 1, as the incremented value is overridden.
9th Nov 2016, 2:40 PM
Rahul Chittimalla
Rahul Chittimalla - avatar
0
if you use b++, you need to recall b++ in a loop, since the value changes after it has been set. in your case, b is declared but it never gets triggered, therefore it stays 1. in the second example you call on b++, therefore it triggers the increment of b
9th Nov 2016, 12:33 AM
Machiel