开发者

Strange behaviour of the increment operators in Java?

I have to pi开发者_如何学编程eces of code:

int m = 4;
int result = 3 * (++m);

and

int m = 4;
int result = 3 * (m++);

After the execution m is 5 and result is 15 in the first case, but in the second case, m is also 5 but result is 12. Why is this the case? Shouldn't it be at least the same behaviour?

I'm specifically talking about the rules of precedence. I always thought that these rules state that parantheses have a higher precedence than unary operators. So why isn't the expression in the parantheses evaluated first?


No - because in the first case the result is 3 multiplied by "the value of m after it's incremented" whereas in the second case the result is 3 multiplied by "the initial value of m before it's incremented".

This is the normal difference between pre-increment ("increment, and the value of the expression is the value after the increment") and post-increment ("remember the original value, then increment; the value of the expression is the original one").


The difference is when the result is assigned to m. In the first case you have basically (not what it really does, but helps to understand)...

int result = 3 * (m=m+1);

In the second case you have

int result = 3 * m; m = m +1;


This is the definition of the operators: m++ evaluates to m, then increments m. It's a "post-increment". Parentheses around it don't change the fact that the operator evaluates to the variable, and also increments it afterward.


Think of it as "increment and get" and "get and increment." For instance, see AtomicInteger, which has the methods incrementAndGet() and getAndIncrement().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜