1

I know this is a silly example, but I do want to know how it works.
In general, post-increment gives the old value and add 1 to the variable after.

int a = 1;
a = a++;
System.out.println(a);

At line3, it prints out "1". why does a remain the same?

In my understanding, At line2, the right hand side assigns 1 to the variable a.

post-increment "++" add 1 to a. Shouldn't it be 2 instead of 1?

Peter Hwang
  • 971
  • 1
  • 12
  • 25
  • 1
    Think about it. A temp copy of `a` is made. Then `a` is incremented. Then the temp copy is assigned to the assignment target (which happens to be `a`). Post-increment is a very dangerous function if you don't think it through carefully. Avoid using it if you can. – Hot Licks Oct 11 '14 at 21:12
  • 2
    [What is x after “x = x++”?](http://stackoverflow.com/q/7911776/1391249) – Tiny Oct 11 '14 at 21:13
  • @HotLicks why not post that comment as an answer? – nmore Oct 11 '14 at 21:14

2 Answers2

5

You can think of a = a++; (in Java) like this:

int tmp = a;
a = a + 1;
a = tmp;

First the value of a is read, then a is incremented, but then a is assigned the value you read in the first place. This is because the expression a++ takes the value of a before the increment. Then, the expression a = ____ happens, assigning the value you got during the a++ to a.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
3

The assignment happens after the increment, using the pre-increment value of a.

That's because the sequence of events for post increment is:

  • use the current value of the variable
  • immediately increment the variable (before any other action)

The effect of the second step is overwritten by the following assignment, which of course uses the ore-increment value as per the first step

Bohemian
  • 412,405
  • 93
  • 575
  • 722