[英]Why is post increment operator in a return statement act different from expected in Eclipse?
I see this post: In Java, how does a post increment operator act in a return statement? 我看到这篇文章: 在Java中,帖子增量运算符如何在return语句中起作用?
And the conclusion is: a post increment/decrement happens immediately after the expression is evaluated. 结论是: 表达式求值后立即发生后增量/后减。 Not only does it happen before the return occurs - it happens before any later expressions are evaluated.
它不仅发生在返回发生之前,而且还发生在对任何后续表达式求值之前。
I tried the sample code in the post like below in Eclipse: 我在Eclipse中尝试了以下示例中的示例代码:
class myCounter {
private int _ix = 1;
public int ixAdd() {
return _ix++ + giveMeZero();
}
public int giveMeZero()
{
System.out.println(_ix);
return 0;
}
}
public class mytest {
public static void main(String[] args) {
myCounter m = new myCounter();
System.out.println(m.ixAdd());
}
}
and the result is: 结果是:
2
1
It shows that _ix
is incremented to 2
in giveMeZero()
as expected. 它显示
_ix
在giveMeZero()
按预期增加到2
。 But ixAdd()
is still returning 1
. 但是
ixAdd()
仍返回1
。
Why is this happening? 为什么会这样呢? Isn't it against what In Java, how does a post increment operator act in a return statement?
这与Java中的后增量运算符如何在return语句中起作用相反吗? is all about?
是全部吗?
Thanks, 谢谢,
Remember that the post increment operator evaluates to the original value before the increment is performed. 请记住,执行增量操作后,后增量运算符将求值为原始值。
This means that eg 这意味着
int a = i++;
is similar to doing: 类似于:
int a = i;
i = i + 1;
That is, a
receives the original value of i
and after that, i
is incremented. 即,
a
接收i
的原始值,然后i
递增。
When used in a return statement, there's no difference, it evaluates to the value before the increment. 当在return语句中使用时,没有区别,它的计算结果为递增之前的值。
return _ix++ + giveMeZero();
would be similar to: 类似于:
int temp = _ix;
_ix = _ix + 1;
return temp + giveMeZero();
Think about the compiler evaluating each part of that return
statement on at a time: 考虑一下编译器一次评估该
return
语句的每个部分:
return _ix++ + giveMeZero();
Is the same as: 是相同的:
int tmp1 = _ix++;
int tmp2 = giveMeZero();
return tmp1 + tmp2;
So by the time giveMeZero
is evaluated, _ix
has already been incremented. 因此,通过时间
giveMeZero
评估, _ix
已经增加。
It is because _ix++ + giveMeZero();
这是因为
_ix++ + giveMeZero();
first return then add 1 to _ix
. 首先返回,然后将
_ix
加1。
if you do ++_ix
then it is OK 如果您使用
++_ix
那就可以了
Note: ++
if first occur it means that firs add one and then do the operation, if occur after then it means that first do that operation then add one 注意:
++
如果首先出现,则表示先加一个,然后再执行该操作;如果之后出现,则意味着先进行该操作,然后再加一个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.