+ 1

Why does this equal 9?

int i = 3; i = ++i + i++; ++i and i++ result in 4 and 3 when alone. So why is i++ incrementing the value when combined with ++i. i = 4 + i++; results in 7 Edit: To everyone saying the i++ increments it to 5, why does it only increment in this specific case?

19th Oct 2016, 6:23 PM
Ted L
Ted L - avatar
3 Antworten
+ 4
First ++i is 4. Second i++ is 5. Then sum them up
19th Oct 2016, 7:06 PM
Remmae
Remmae - avatar
+ 3
Actually, `++i + i++` doesn't equal anything! It is undefined behaviour, and those are words that every C++ programmer is scared of. The thing is that both `++i` and `i++` produce so-called "side effects", that is, they increment the value of `i`, and the C++ standard gives no guarantee about what side of the `+` operator is executed first. Undefined behaviour means you may likely see different compilers give different results, so you can't rely on it yielding `9` at all.
19th Oct 2016, 7:26 PM
Schindlabua
Schindlabua - avatar
- 1
when I is defined to be ++I + I++ , I is incremented once cos of the pre-increment and the value of ++I and I++ is 4.. and then , when you print it.. the post-increment statement is done in the cout statement and we get 4+4+1 is equal to 9
19th Oct 2016, 6:37 PM
Karthik Ambu
Karthik Ambu - avatar