在Java中,post增量运算符如何在return语句中起作用? [英] In Java, how does a post increment operator act in a return statement?

查看:144
本文介绍了在Java中,post增量运算符如何在return语句中起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于以下代码,ixAdd会做你期望的,i。即在递增之前返回ix的值,但在离开函数之前递增类成员?

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++;
    }
}

我不太确定是否通常的规则当程序离开函数的堆栈帧(或Java中的任何内容)时,post / pre increment也适用于return语句。

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.

推荐答案

关键部分是在计算表达式后,立即发生后增量/减量。它不仅在返回发生之前发生 - 它发生在任何后续表达式被评估之前。例如,假设您写道:

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:

class myCounter {
    private int _ix = 1;

    public int ixAdd()
    {
        return _ix++ + giveMeZero();
    }

    public int giveMeZero()
    {
        System.out.println(_ix);
        return 0;
    }
}

这也会打印出递增的结果,因为增量发生在之前调用giveMeZero()

That would print out the incremented result as well, because the increment happens before giveMeZero() is called.

这篇关于在Java中,post增量运算符如何在return语句中起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆