0

How C++ postfix incrementation works?

Why output of below code is 5? int b = 1; b=++b+b++; cout<<b; and output of this code is 1? int b = 1; b=b++; cout<<b; Why in first example the b++ incrementation is added to result and in second case it is not? How does it work?

11th Jan 2017, 3:40 PM
Marcin BaraƄczyk
Marcin BaraƄczyk - avatar
1 Answer
0
Just don't use multiple incrementations in the same line, it will only mess up the result! What happens is that there are two increments, so b will be calculated to be 3 for the (++b) case and 2 for the (b++) case. 2+3 = 5 so the result is 5. In the second example you calculate b++ first, but then set b to the old value of be, in this case 1.
11th Jan 2017, 4:00 PM
Robobrine
Robobrine - avatar