This question already has an answer here:
- What is x after “x = x++”? 17 answers
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 ?
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++
:
- Get the value of
b
into some temp (probably into a bytecode register); this is the first part ofb++
, since it's a post-increment - Increment and store the incremented result in
b
(the second part ofb++
) - 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.
来源:https://stackoverflow.com/questions/27621242/difference-between-b-b-and-b