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

前端 未结 5 1159
忘了有多久
忘了有多久 2020-12-11 14:53

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?

相关标签:
5条回答
  • 2020-12-11 15:50

    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.

    0 讨论(0)
  • 2020-12-11 15:50

    Yes, it does.

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

    0 讨论(0)
  • 2020-12-11 15:50

    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.

    0 讨论(0)
  • 2020-12-11 15:53

    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.

    0 讨论(0)
  • 2020-12-11 15:55

    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.

    0 讨论(0)
提交回复
热议问题