-2

I'd like to know why a postfix increment on a value being returned in a return statement is not evaluated if the increment occurs on the righthand side of the return statement.

I know that the value returned should be the pre-increment value, but assuming a class-level variable, the increment should still show up in the variable itself.

Here is my example.


public class ReturnDemo {

static int val=1;

public static void main(String[] args)
{
    System.out.println(getVal());
    System.out.println(val);


}
public static int getVal()
{
    return(val=(val++));
}

}


I would have expected this to print out 1 2 but it actually printed out 1 1

If you do the same thing without the assign, it increments correctly.

This, for example:


public class ReturnDemo {

static int val=1;

public static void main(String[] args)
{
    System.out.println(getVal());
    System.out.println(val);


}
public static int getVal()
{
    return(val++);
}

}


Returns 1 2 (It gets val at 1 then increments the variable val to 2.)

Why is it that there is a line drawn in the sand at evaluating the postfix increment within a return statement if it's on the righthand side of an assignment, but that same line is not applied to postfix increments that are not part of an assignment statement?

Mer
  • 762
  • 1
  • 6
  • 12
  • The short answer is that it >>is<< incremented, but the incremented value is then thrown away. For more details, please refer to the linked Question and its Answers – Stephen C Jun 08 '14 at 00:32

1 Answers1

2

The return is a red herring. The problem is val=(val++), which is Just Plain Ugly and Bad Practice.

val++ is post-increment. In other words, this subexpression returns the previous value of val, then increments the variable.

So you are telling the compiler you want to obtain the previous value of val (1), then increment it (2), then assign that previous value to val -- setting it back to 1 again. The program is doing exactly what you told it to do.

You're trying too hard. If you want to return the value of val after it has been incremented, you can use return ++val;. If you want to increment val but return the previous value, use return val++;.

keshlam
  • 7,931
  • 2
  • 19
  • 33
  • Thanks. I believe that between this and the prior thread provided by Stephen, I understand what is happening. I'd interpreted i=i++; as having 2 steps: 1. (i from LHS)=(i from RHS); 2. (i from RHS)++; When it is in 3 steps, such that i=i++; translates to: 1. temp=(i from RHS); 2. (i from RHS)++; 3. (i from LHS)=temp; The whole thing makes more sense. I did not realize that the third step was postponed until after the increment, and taken from a temp value. Thanks to you both for your help. – Mer Jun 08 '14 at 07:09