++i + ++i + ++i in Java vs C

前提是你 提交于 2019-11-27 03:36:06

问题


int i=2;
i = ++i + ++i + ++i;

Which is more correct? Java's result of 12 or C = 13. Or if not a matter of correctness, please elaborate.


回答1:


There is nothing like more correct. It is actually undefined and its called Sequence Point Error. http://en.wikipedia.org/wiki/Sequence_point




回答2:


Java guarantees (§15.7.1) that it will be evaluated left-to-right, giving 12. Specifically, ++ has higher precedence that +. So it first binds those, then it associates the addition operations left to right

i = (((++i) + (++i)) + (++i));

§15.7.1 says the left operand is evaluated first, and §15.7.2 says both operands are evaluated before the operation. So it evaluates like:

i = (((++i) + (++i)) + (++i));
i = ((3 + (++i)) + (++i)); // i = 3;
i = ((3 + 4) + (++i)); // i = 4;
i = (7 + (++i)); // i = 4;
i = (7 + 5); // i = 5;
i = 12;

In C, it is undefined behavior to modify a variable twice without a sequence point in between.




回答3:


The Java result makes sense to me because the operators give the result you would expect, but no serious program should contain a statement like this.

EDIT: I'm amused that this one sentence response has been my highest scored answer of the evening (compared to the dozen other answers I posted, some with pages of code samples). Such is life.




回答4:


In C this is undefined behavior. There is no correct behavior.



来源:https://stackoverflow.com/questions/3879176/i-i-i-in-java-vs-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!