Sigh, where did this come from?
main() == wrong. It's int main(). Get it right. Now onto the real problem.
++i+i+++(--i) --> (++i) + (i++) + (--i)
Anyone see the problem here? If you don't, see: http://c-faq.com/expr/ieqiplusplus.html
i++ causes a side effect. It returns i, and then increments i later on. The problem is the exact moment that side effect happens is undefined. Is it ++i + i + --i and then increment i by 1? Is it ++i + i, increment i by one, and then + --i?
Former case:
++i = 4, + i = 8, + --i = 11. Then after printf shows 11, i gets incremented to 4.
Latter case:
++i = 4, + i = 8, i incremented by one to 5. Then + --i = 12. So printf shows 12.
The standard doesn't say precisely when the side effect must occur. In short, undefined behavior. If this is a homework question, and I was the teacher, I would mark both 11 and 12 as wrong. The answer is *undefined*.
2006-12-30 07:23:48
·
answer #1
·
answered by csanon 6
·
1⤊
0⤋
Are there other homework questions too?
Think about the different operators in C. You have +, ++, and -- in the above. There is only one set of parens and no spaces, so that doesn't help see it. If they were used, it would look like the following:
printf("%d", ++i + i++ + (--i) );
or better yet
printf("%d", (++i) + (i++) + (--i) );
Remember, the ++ in front of the variable means to perform the increment BEFORE using the variable, while the ++ following the variable means to increment AFTER using the variable.
The answer is 12 - you figure out how it got that.
2006-12-30 14:01:44
·
answer #2
·
answered by BigRez 6
·
0⤊
0⤋
The above user has a good explanation, but the actual output is:
11
Edit:
It SHOULD be 12... I wonder why it's giving me 11 when actually tested with gcc.
2006-12-30 14:04:25
·
answer #3
·
answered by Chris 2
·
0⤊
0⤋
u see it as (++i) + (i++) + (--i),now since + and - operator have left to right associativity(i.e. computation takes from right to left) so sequence would be ++i (4) + i++ (4 : would be 5 after this step) + --i(4 :5-1)...answer is 12......i hope this helps...
2006-12-30 14:18:32
·
answer #4
·
answered by AM 3
·
0⤊
0⤋