Difference between b = b ++ and b ++

In an interview, I was asked the question below.

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

      

what will be the value of b after each execution of the line? The output is 0 for each row.

Why doesn't the output come as 0,1,2,3?

+3


source to share


4 answers


In Java, the expression

b = b++

      

equivalent to



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

      

Hence the result.

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

+6


source


Since this is the order of execution b = b++

:



  • Get the value b

    at some pace (possibly into a bytecode register); this is the first part b++

    as it is post increment
  • Incrementing and storing the incremented result in b

    (second part b++

    )
  • Assign value from step 1 to b

    (result =

    )
+2


source


Hint:

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

      

c

it will now be 3 as you thought, but since in your question you are assigning b

it will get 0, because as already explained it is the same as:

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

      

+2


source


b++

matches:

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

      

As you can see, b++

will return its previous value, but overwrite the value b

. But since you assigned the return (old) value to b

, the new value will be overwritten and therefore "ignored".

The difference would be if you write:

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

      

In this case, the increment is performed and the new value will be returned.

+1


source







All Articles