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

微笑、不失礼 提交于 2020-01-10 20:00:10

问题


I was asked in an interview the below question.

int b = 0;
b = b++;
b = b++;
b = b++;
b = b++;

what will be the value of b after every line execution ? The output is coming as 0 for every line.

Why is the output not coming as 0,1,2,3 ?


回答1:


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.)




回答2:


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;



回答3:


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 =)



回答4:


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.



来源:https://stackoverflow.com/questions/27621242/difference-between-b-b-and-b

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