简体   繁体   中英

In Java, how does a post increment operator act in a return statement?

Given the following code, will ixAdd do what you'd expect, ie 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.

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

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

Well, let's look at the bytecode (use javap -c <classname> to see it yourself):

Compiled from "PostIncTest.java"
class myCounter extends java.lang.Object{
myCounter();
  Code:
   0:   aload_0
   1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
   4:   aload_0
   5:   iconst_1
   6:   putfield    #2; //Field _ix:I
   9:   return

public int ixAdd();
  Code:
   0:   aload_0
   1:   dup
   2:   getfield    #2; //Field _ix:I
   5:   dup_x1
   6:   iconst_1
   7:   iadd
   8:   putfield    #2; //Field _ix:I
   11:  ireturn

}

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 a dup instruction before these two appear; the incremented value is (of course) not reflected in the return value.

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.

Yes, it does.

But don't do that, it is bad style to have side effects in expressions.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM