4 ms·
Could someone explain why in question 5 i = 0; return i++ + ++i; Could produce different results?
by raviolo 7y ago
Could someone explain why in question 5
i = 0;
return i++ + ++i;
Could produce different results?
- detaro 7y agoThere's explanations at the bottom after you click the button.
- raviolo 7y agoI read it but I still don’t understand. Isn’t it 0 + 2 vs 1 + 1? How would it produce something other than 2?
- JKCalhoun 7y agoHow do you get 0 + 2? I could imagine the post-increment happening after the sum: giving 0 + 1…
- dahart 7y agoThat’s what I imagined, and what I get with Cygwin gcc, the result is 1. I thought that the post-increment was supposed to always only happen after the “statement”, but I was wrong. Other compilers, like gcc on Ubuntu return 2. This looks like a good explanation of why both are correct and why it’s confusing: https://stackoverflow.com/a/4445841 https://stackoverflow.com/a/4445841
- raviolo 7y agoSo for the left-to-right operand evaluation order I thought it’s this: look at the left operand, take zero. Then post-increment, now it’s one. Move on to the right operand. Pre-increment what is 1, so now it’s 2. Take 2. So it 0 + 2?
- Dylan16807 7y agoImagine a dumb piece of hardware storing your variables. Two pieces of a statement try to do conflicting things to the same variable at the same time. This can cause the data to get corrupted, or the entire chip to have a fault. The C standard allows an implementation like this.