user1559625
user1559625

Reputation: 2673

Why is post increment operator in a return statement act different from expected in Eclipse?

I see this post: In Java, how does a post increment operator act in a return statement?

And the conclusion is: 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.

I tried the sample code in the post like below in Eclipse:

class myCounter {
    private int _ix = 1;

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

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

public class mytest {
    public static void main(String[] args) {
        myCounter m = new myCounter();
        System.out.println(m.ixAdd());
    }
}

and the result is:

2

1

It shows that _ix is incremented to 2 in giveMeZero() as expected. But ixAdd() is still returning 1.

Why is this happening? Isn't it against what In Java, how does a post increment operator act in a return statement? is all about?

Thanks,

Upvotes: 0

Views: 1147

Answers (3)

nos
nos

Reputation: 229088

Remember that the post increment operator evaluates to the original value before the increment is performed.

This means that e.g.

int a = i++;

is similar to doing:

int a = i;
i = i + 1;

That is, a receives the original value of i and after that, i is incremented.

When used in a return statement, there's no difference, it evaluates to the value before the increment.

return _ix++ + giveMeZero();

would be similar to:

int temp = _ix;
_ix = _ix + 1;

return temp + giveMeZero();

Upvotes: 3

Buddy
Buddy

Reputation: 11028

Think about the compiler evaluating each part of that return statement on at a time:

 return _ix++ + giveMeZero();

Is the same as:

int tmp1 = _ix++;
int tmp2 = giveMeZero();
return tmp1 + tmp2;

So by the time giveMeZero is evaluated, _ix has already been incremented.

Upvotes: 2

Bahramdun Adil
Bahramdun Adil

Reputation: 6079

It is because _ix++ + giveMeZero(); first return then add 1 to _ix.

if you do ++_ix then it is OK

Note: ++ if first occur it means that firs add one and then do the operation, if occur after then it means that first do that operation then add one

Upvotes: 0

Related Questions