4

What is happening in the code below?

public static void main (String[] args) {
    int x = 5;
    x = x++;
    System.out.println(x);  // 5. So what happened to the ++?
}

I can understand x is assigned the value 5, because we told it to take the value before increment.

However, it must still do the increment, so is this done on a temporary value?

I don't understand Java bytecode but it dissassembles as follows.

  public static void main(java.lang.String[]);
Code:
   0: iconst_5
   1: istore_1
   2: iload_1
   3: iinc          1, 1
   6: istore_1
   7: getstatic     #2                  // Field java/lang/System.out:Ljava/io/PrintStream;
  10: iload_1
  11: invokevirtual #3                  // Method java/io/PrintStream.println:(I)V
  14: return

I can't see where it's creating a temp. What's really going on?

1 Answers1

1

However, it must still do the increment, so is this done on a temporary value?

Why? If the operation has no visible effect, there is no need to perform it.

What happens here is:

  1. the expression x++ is evaluated. The result is 5.
  2. the variable x is incremented, as a side effect the ++ operator.
  3. the variable x is assigned the value of the expression in (1), which is 5,

At the end x unambigously has the value 5. An optimising compiler can remove the ++ operation, since it has no effect on the final value of x, or any other part of the program.

In the case of Java, optimisations occur not only in the compiler but also in the runtime. Therefore, even if the assembly contains "iinc", this could well be optimised away later.

Here is an example of optimised C compiler output. As you can see it doesn't contain the increment operation:

https://godbolt.org/g/2iTLhZ

Note: your compiler may warn that the expression "may be undefined". This is because in C, the right-hand and left-hand sides of an assignment are evaluated in an unspecified order. As we can see, either order gives the same result in this particular example (since the left-hand side is a constant reference) but it's something to be aware of.

jforberg
  • 6,537
  • 3
  • 29
  • 47