Hanno Fietz
Hanno Fietz

Reputation: 31400

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

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.

Upvotes: 16

Views: 11234

Answers (5)

Eddie
Eddie

Reputation: 54431

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.

Upvotes: 1

trilobite
trilobite

Reputation: 316

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.

Upvotes: 0

Michael Myers
Michael Myers

Reputation: 192055

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.

Upvotes: 16

starblue
starblue

Reputation: 56832

Yes, it does.

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

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1504004

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.

Upvotes: 28

Related Questions