+ 1

"Please, explain yourself!" ++i + i++

Please, explain the feature of: int i = 1; cout << ++i + i++; /* output: 5 */ Why?

2nd Dec 2016, 11:01 PM
Pavel
Pavel - avatar
8 Answers
+ 6
Here is a clear example: x = 5; y = ++x; This means to increment x first then assign its value to y. In this case, y will be equal to 6 and x will be equal to 6. x = 5; y = x++; This means to assign the value of x to y and then increment x. In this case, y will be equal to 5 and x will be equal to 6.
2nd Dec 2016, 11:59 PM
User3827
+ 3
I think that question is the most answered question in the last weeks. ++i is prefix notation and means i = i+1; i++ is postfix notation and means i= i + 1; The difference is how the statements get executed. Prefix means that you execute it directly and use your incremented value. Postfix means you use the value before incrementation and increment it afterwards.
2nd Dec 2016, 11:35 PM
Andreas K
Andreas K - avatar
+ 1
The post increment runs caus its in a calculation. cout has to wait till the value to print is calculated and due to the postfix notation, the calculation is in this case finoshed when I got incremented
3rd Dec 2016, 11:33 AM
Andreas K
Andreas K - avatar
0
AKCodingBlog, according to your explanation it has to be: (1+1) + 2 = 4
2nd Dec 2016, 11:43 PM
Pavel
Pavel - avatar
0
Pavel, you forgot to increment in the last part. we divide your expression: int i = 1; ++i // this increments i to 2 + ++i // this adds 2 on i so i is 4 ; // after your calculation you increment i again, because of postfix notation. so i is 5; // <--- now you output i
3rd Dec 2016, 12:04 AM
Andreas K
Andreas K - avatar
0
Okay, I'll try to reconstruct my question: why postfix increment is triggering before "cout"? It's look like posrfix don't increment it afterwards.
3rd Dec 2016, 4:48 AM
Pavel
Pavel - avatar
0
Thanks to everyone.
3rd Dec 2016, 11:40 AM
Pavel
Pavel - avatar
0
E
4th Oct 2020, 1:33 PM
Abhay Parmar
Abhay Parmar - avatar