Basic arithmetic and increment operator | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Basic arithmetic and increment operator

It's easy to see the output for int a = 4, b; b=a+a cout<<b This gives 8 because b = 4+4 What if instead of cout<<b, we ask for b++? Why does the computer still give us 8 and not 9? From my understanding, b++ is equivalent to b=b+1. If b=8, why does the computer not print 9 for b++?

19th Jul 2020, 8:04 AM
Solus
Solus - avatar
2 Answers
+ 2
because b++ is a post-increment. it cout (print) b then increment it to 9. if you add another cout << b ; you get 9. like : cout << b++; // 8 cout << b; // 9 if you need to increment it then cout (print) , use cout << ++b; basically the difference between post-increment b++ and pre-increment ++b.
19th Jul 2020, 8:29 AM
Bahhaⵣ
Bahhaⵣ - avatar
+ 3
Solus If you will directly print b++ then output will be 8 Because It's post Increment which First assign the value then Increment value by 1 Just print it and see what you get int b = 8; cout << b++ << "\n"; cout << b;
19th Jul 2020, 8:28 AM
A͢J
A͢J - avatar