1

I'm having a program that prints the value of an integer number x after a post-increment operation. I want to know what actually happened during that operation?

The post-increment operator first assign the value then increment it but this didn't happen in the first example, I don't know if this because it is assigned to the same variable x so the memory will not be affected twice on the same variable in one operation!

int x = 1; //x = 1
x = x++; //x = 1 
System.out.println(x); //x = 1
int x = 1; //x = 1
int y = 1; //y = 1
y = x++; //y = 1, x = 2
System.out.println(x); //x = 2

I expect the output of x to be 2, but the actual output is 1

Ahmed Maad
  • 367
  • 5
  • 16
  • 4
    The assignment to `x` takes place after the postincrement, but it uses the preincrement value. – user207421 Aug 06 '19 at 13:14
  • 1
    It also makes no sense to write it like that in any case whatsoever, as entire assignment expression will evaluate to x too. In worst case, in languages like C++, it will be undefined behaviour, which is even worse than unreadable "NOP". –  Aug 06 '19 at 13:20
  • I didn't know that thanks a lot @user207421 – Ahmed Maad Aug 06 '19 at 13:28

0 Answers0