I just learned that if a return statement contains an increment operation, the return will execute first and the value will be returned before it is incremented. If I increment first in a separate statement, and then return, it works as expected.
private static int incrementIntV1(int a)
{
return a++;
}
private static int incrementIntV2(int a)
{
a++;
return a;
}
public static void main(String[] args)
{
int b = 6;
System.out.println("Increment in return: " + incrementIntV1(b));
System.out.println("Increment first, then return: " + incrementIntV2(b));
System.out.println("Increment with addZero: " + incrementAddZero(b));
}
What is happening with return that makes it sometimes evaluate the whole expression and sometimes not? Is this something special about how the increment operation happens?
If I try:
private static int incrementAddZero(int a)
{
return a++ + addZero();
}
private static int addZero()
{
System.out.print("addZero executes");
return 0;
}
The increment operation still doesn't happen, but I know that the addZero method runs because of the print statement. Why doesn't it increment before the return but it does execute the addZero method before the return?
Hope his makes sense. Thank you much.
The behavior you encountered has nothing to do with the return statement. It's the behavior of the post increment operator. The expression a++
increments a
but returns the previous value of a
.
return a++;
is equivalent to :
int x = a++;
return x;
similary,
return a++ + addZero();
is equivalent to :
int x = a++ + addZero();
return x;
or to :
int x = a++;
return x + addZero();
a++
returns the value of a
before it was incremented.
What is happening with return that makes it sometimes evaluate the whole expression and sometimes not?
return
always evaluates the whole expression being returned (unless the return statement contains some short circuited operator such as &&
and ||
, but that's not the case here), but the evaluation of the post increment operator a++
returns the old value of a
.