Explain what happens to the ++ operator in "x = x ++;". Where is the increment performed?

What happens 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 understand that x is assigned the value 5, because we told him to accept the value before the increment.

However, he still has to do the increment, so what is this done on a temporary basis?

I do not understand Java bytecode, but it is parsed 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 do not see where it creates temp. What is really going on?

+4
source share
1 answer

However, he still has to do the increment, so what is this done on a temporary value?

Why? If the operation does not have a visible effect, there is no need to perform it.

What is going on here:

  • The expression x ++ is evaluated. The result is 5.
  • x , ++.
  • x (1), 5,

x 5. ++, x .

Java , . , "iinc", .

C. , :

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

: , " undefined". , C . , ( ), , .

+1

Source: https://habr.com/ru/post/1657087/


All Articles