java – Why is 0 displayed?

Question:

There is a code:

int i =0;
i = i++;
System.out.println(i);

Will output 0 to the console.

The question is why – 0 ?

Answer:

  • Offtop about such construction in C++

This code can output 0, 1 and, generally speaking, anything. i = i++ is undefined behavior by the standard.

  • There is a standard which defines such concept as sequence point. So, parsing this expression in the light of these same sequence points involves a double change in the value of i between two sequence point'ами . Which by standard leads to undefined behavior.

  • You can read more here.


  • In Java everything is simpler – the given code unambiguously corresponds to the following code. More – here.

     int temp = i; // temp = 0 i++; // i = 1 i = temp; // i = 0
Scroll to Top