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 ?
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.)
Because this is the order of execution of b = b++
:
b
into some temp (probably into a bytecode register); this is the first part of b++
, since it's a post-incrementb
(the second part of b++
)b
(the result of the =
)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;
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.