Question

In this code segment,

[1]int i=0;
[2]i = i++; 
[3]System.out.println(i);

In line 2, it is executed the expression first (which is assigned 0 to i) and then it should increment the value by 1.

In System.out.println(i) , I am getting the answer as 0 instead of 1.Can someone explain the reason for this?

Was it helpful?

Solution

i++ does not yield a variable, but a value.

  1. i++ yields 0.

  2. Then i is incremented to 1.

  3. Then 0 is assigned to i.

Summary: the precedence of operators is maybe not what you expected. Or at least you might've misunderstood where the actual increment of i is happening. It's normal to show people that use of i++ can be split into 2 lines where the line after is doing the incrementation - that's not always correct. It happens before the assignment operator.

OTHER TIPS

The assignment first saves the value of i, then sets i to its value plus 1, and, finally, resets i back to its original value. Kind of:

int temp=i;
i=i+1;
i=temp;

@chathura2020 : go to this link.It is about Sequence points.

Sequence points also come into play when the same variable is modified more than once within a single expression. An often-cited example is the C expression i=i++ , which apparently both assigns i its previous value and increments i. The final value of i is ambiguous, because, depending on the order of expression evaluation, the increment may occur before, after, or interleaved with the assignment. The definition of a particular language might specify one of the possible behaviors or simply say the behavior is undefined. In C and C++, evaluating such an expression yields undefined behavior.

(This is not true for java)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top