'Java post increment vs opcode iinc

Most of us are familiar with post increment, but when I look to the bytecode instructions, it shows the increment happened before the invocation to the method.

Example:

int x = 0;
aMethod(x++);

bytecode:

0: iconst_0
1: istore_1
2: iload_1
3: iinc          1, 1
6: invokestatic  #2                  // Method aMethod:(I)V
9: return

Can someone clarify this?



Solution 1:[1]

Thanks to @voo

I've made a another example for pre increment for comparison purpose:

0: iconst_0
1: istore_1
2: iinc          1, 1
5: iload_1
6: invokestatic  #2                  // Method aMethod:(I)V
9: return

The difference can be seen in instruction 2# and 5# (iinc invoked before iload_1), while in in post increment, iload_1 invoked before iinc.

That means the increment will occur on the variable itself and not on the copy pushed onto the stack, which been used as parameter to invoke the method.

from here:

iinc

Increment local variable by constant

The index is an unsigned byte that must be an index into the local variable array of the current frame (ยง2.6). The const is an immediate signed byte. The local variable at index must contain an int. The value const is first sign-extended to an int, and then the local variable at index is incremented by that amount.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Abdullah D.