English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

5 answers

The result is i*i, or 4 in your case.
The statement "i++" uses the post-incremental operator, meaning the variable is incremented AFTER the expression is evaluated. So both uses of "i" are evaluated for the multiplication (which has a higher precendence than the post-incremental operator), the result of the multiplication is stored, and THEN both ++ operators are executed.
You'd wind up with i*i, and then i would be incremented twice, so it would have a value of 2 more than it did before evalutation of the expression.

This is the kind of code writing that gets people in trouble, by the way -- it's horribly obfuscated. It would be much better to write something like:

x = i*i;
i++;
i++;

That way the meaning is clear. You wouldn't just add 2 to i (as in "i+=2"), since it might be a pointer or other non-numeric value, with the incremental operator can properly execute an increment for.

2006-10-30 05:34:47 · answer #1 · answered by Anonymous · 0 0

All three answers so far are WRONG.

The result of an expression like this is UNDEFINED by the C standard. Each compiler writer can apply the two increments in any order he wants relative to the multiplication.

The result can therefore be different on different compilers and different processors, and even (although not likely) different from one run to another with the same compiler and processor.

If the result is consistent on one particular compiler and processor, you can logically explain why, and you can choose to rely on it, but the moment you change your compiler or processor, all bets are off again.

2006-10-30 06:01:02 · answer #2 · answered by Anonymous · 0 0

Its worse then that, the behavior could even change from a debug to a release build.... Imagine how much fun that could be!

In fact anything at all might happen, it could stomp on other variables, format your hard disk (But I would have words with that compiler author), send your porn collection to your mother, make demons fly out of your nose... All would be compliant with the C standard (It could even give a 'reasonable' result).

I have no idea why this question seems so popular.

Regards, Dan.

2006-10-30 07:10:35 · answer #3 · answered by Dan M 3 · 0 1

the answer is 9. this is because the ++ operator increments the number up by one. if i = 2 then (2+1)*(2+1)= 9

2006-10-30 05:31:32 · answer #4 · answered by meanburrito920 2 · 0 0

6

i = 2 when you use it the first time and it is postincremented to 3.
i = 3 when you use it the second time and it is postincremented to 4.

2006-10-30 05:39:20 · answer #5 · answered by novangelis 7 · 0 0

fedest.com, questions and answers