+ 1

Dont understand this outputs.....

I know the difference between pre increment and post increment but i dont understand the following: If b = 3; why b = ++b + b++ outputs 9. and b = b++ + ++b outputs 8. Anyone can explain why this happens and the order of resolution of this assignement.

19th Dec 2016, 6:36 PM
Telmo Pinto
Telmo Pinto - avatar
8 Respostas
+ 2
b = 3; why b = ++b + b++ outputs 9. Reason : Remember that the code still reads from left to right, so hence since the prefix came first, you add 1 to b first, which makes b into 4. So you can read the code as this = { b = (4 + 4)+1 }. Notice the +1? remember that it is a postfix at the end so it is NOT 4 + 4 +1, it is (4+4)+1. (These things matters when you have longer equations) b = b++ + ++b outputs 8 Again, reading from left to right, we simplify it to {b = [3 + (3+1)]+1}. In short, the prefix didn't came first, so b stayed as '3' during the postfix and prefix.
19th Dec 2016, 8:25 PM
Wen Qin
Wen Qin - avatar
+ 2
b = 3; b = b++ cout << b; //output is 3. why? shouldnt be 4? Reason : This is slightly similar to a situation with this { b =3; y = 3; b = y++; } b will just become 3, y will become 4. But the case you stated will be different, in that case, b will just simply be 3 and the b will again be... 3. If you want a even more detailed explaination, place the code into an IDE and run it using the debugger.
19th Dec 2016, 8:58 PM
Wen Qin
Wen Qin - avatar
+ 2
1) ++x returns x after its value increased by 1 2) x++ returns a new value equals the value of the original x, but x value also increased. So: x++ + ++x = x + ++x (where x=4) = x + y (where x=5,y=4) = 9
20th Dec 2016, 3:19 PM
DFX
DFX - avatar
0
There are various questions like yours on Sololearn. Simply put, you would never ever write code like that. Side effects used wildly tend to introduce bugs in your code. In the worst case scenario you may even end up with code whose behaviour is compiler dependent.
19th Dec 2016, 6:53 PM
Giulio Pellitta
Giulio Pellitta - avatar
0
When you are calculating the second part(b++) the variable "b" has already been increased by 1 by the first part(++b). Then: b=3; ++b-> b= 4 b++-> b= 5 (++b) + (b++) = 4+5 = 9
19th Dec 2016, 6:56 PM
alonfeclab
alonfeclab - avatar
0
Yes i know i would never use that code. i am only asking because i saw a similar expression in a question of a sololearn challenge.
19th Dec 2016, 7:00 PM
Telmo Pinto
Telmo Pinto - avatar
0
k2 Shape but this code: b = 3; b = b++ cout << b; //output is 3. why? shouldnt be 4?
19th Dec 2016, 8:51 PM
Telmo Pinto
Telmo Pinto - avatar
0
ok. thanks for your time.
19th Dec 2016, 9:04 PM
Telmo Pinto
Telmo Pinto - avatar