+ 1

Why are the results different?

#include <iostream> using namespace std; int main() { int i=3; int b=4; cout<< ++i + b++; return 0; } Result is 8. #include <iostream> using namespace std; int main() { int i=3; cout<< ++i + i++; return 0; } Result is 9. Why are the results different?

2nd Aug 2017, 3:14 PM
A.Kaan AYDIN
2 Respostas
+ 11
In the first case, i is incremented prior to statement evaluation, while b is incremented after statement evaluation. During evaluation, i is 4 and b is 4. Outputs 8. As for the second case, it has a catch. https://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points
2nd Aug 2017, 3:59 PM
Hatsy Rei
Hatsy Rei - avatar
+ 1
case 1: i=3; b=4; cout ++i (prefix) mean it will increase 1 that mean 4; b++(safix)that mean it will increase after , practical it will be in the same position b=4 in this situation so the answer is 8; second case: i=3 ++i mean (prefix) 1 increment i++ mean (safix) remain at the same position in this situation. so actually the answer in addition we get 7 not 9.
2nd Aug 2017, 4:20 PM
Irwin Lopez
Irwin Lopez - avatar