在 Java 中,后自增运算符在 return 语句中如何起作用?
给定以下代码, ixAdd 是否会执行您所期望的操作,即在递增之前返回 ix 的值,但在离开函数之前递增类成员?
class myCounter {
private int _ix = 1;
public int ixAdd()
{
return _ix++;
}
}
当程序离开函数的堆栈帧(或 Java 中的任何内容)时,我不太确定后/前增量的常见规则是否也适用于 return 语句。
Given the following code, will ixAdd do what you'd expect, i. e. return the value of ix before the increment, but increment the class member before leaving the function?
class myCounter {
private int _ix = 1;
public int ixAdd()
{
return _ix++;
}
}
I wasn't quite sure if the usual rules for post / pre increment would also apply in return statements, when the program leaves the stack frame (or whatever it is in Java) of the function.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
关键部分是在表达式求值后立即发生后递增/递减。 它不仅发生在返回发生之前 - 它发生在计算任何后续表达式之前。 例如,假设您写道:
这也会打印出递增的结果,因为递增发生在调用
giveMeZero()
之前。The key part is that 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. For instance, suppose you wrote:
That would print out the incremented result as well, because the increment happens before
giveMeZero()
is called.好吧,让我们看一下字节码(使用
javap -c
自己看看):如您所见,
ixAdd()
中的指令6和7处理返回前的增量。 因此,正如我们所期望的,递减运算符在 return 语句中使用时确实有效果。 但请注意,在这两个指令出现之前有一个 dup 指令; 增加的值(当然)不会反映在返回值中。Well, let's look at the bytecode (use
javap -c <classname>
to see it yourself):As you can see, instructions 6 and 7 in
ixAdd()
handle the increment before the return. Therefore, as we would expect, the decrement operator does indeed have an effect when used in a return statement. Notice, however, that there is adup
instruction before these two appear; the incremented value is (of course) not reflected in the return value.是的,它确实。
但不要这样做,在表达式中产生副作用是不好的风格。
Yes, it does.
But don't do that, it is bad style to have side effects in expressions.
是的,即使在退货声明中,通常的规则也适用于后期增量。 基本上,它将在低级别执行的操作是将返回值存储到寄存器中,然后递增类成员,然后从方法返回。
您可以在 此问题的稍后答案显示了字节码。
Yes, the usual rules apply for post increment even on a return statement. Basically, what it will do at a low level is store the return value into a register, then increment the class member, then return from the method.
You can see this in a later answer to this question that showed the byte code.
它确实返回增量之前的值,然后增量_ix。 因此,第一次在 myCounter 实例上调用 ixAdd 方法时,它将返回 1,第二次将返回 2,依此类推。
It does return the value before the increment, and then increment _ix. Therefore the first time you call the method ixAdd on an instance of myCounter it will return 1, the second time it will return 2, and so on.