Difference between b=b++ and b++ [duplicate]

烂漫一生 提交于 2019-11-30 23:38:48
NPE

In Java, the expression

b = b++

is equivalent to

int tmp = b;
b = b + 1;
b = tmp;

Hence the result.

(In some other languages, the exact same expression has unspecified behaviour. See Undefined behavior and sequence points.)

Hint:

int b = 0, c;
c = b++;
c = b++;
c = b++;
c = b++;
System.out.println(c);

c now will be 3 like you thought, but because in your question you're assigning b, it'll get 0, because as already explained, it's the same as:

int tmp = b;
b = b + 1;
b = tmp;

Because this is the order of execution of b = b++:

  1. Get the value of b into some temp (probably into a bytecode register); this is the first part of b++, since it's a post-increment
  2. Increment and store the incremented result in b (the second part of b++)
  3. Assign the value from Step 1 to b (the result of the =)

b++ is the same as:

int temp = b;
b = b + 1;
return temp;

As you can see b++ will return his old value, but overwrites the value of b. But since you assign the returned (old) value to b, the new value will be overwritten and therefore "ignored".

A difference would be, if you write:

b = ++b; //exactly the same as just "++b"

This does the incrementation first and the new value will be returned.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!