Reputation: 81
This is an example I found on a website. The result is really different from what I expected. But there is no further explain.
int num = 0;
for (int i = 0; i < 3; ++i)
{
num += num++;
}
System.out.println(num);
Finally, the result will print 0
. I am really confused about the operation num += num++
. Can someone explain this?
Upvotes: 2
Views: 180
Reputation:
This assignment
num += num++;
invokes two different rules in java: one on the left side, one on the right side.
The right side rule is fairly well known: the value of the post-increment operator is the value of the variable before the increment. This makes the value of 0++
a zero.
The other rule is a bit more obscure (I was not aware of the left side rule).
According to "15.7.1. Evaluate Left-Hand Operand First" in Java Language Specification Java first decides just what gets assigned, and also what is its value. Then the right side of +=
is computed.
With these two rules in mind, the assignment above is the equivalent of:
temp1 = num // and will assign to num
temp2 = num // before ++
num = num + 1
num = temp1 + temp2
As you can see, the last line adds the original value of num
(it happens to be 0
) to the value of num
before ++, which ensures that num
does not change. It starts at 0
, it ends with 0
.
Suppose that you're now using a pre-increment operator:
num += ++num;
Now the situation is sligthly different.
int temp1 = num // and num will be assigned
int temp2 = num = num + 1
num = temp1 + temp2
The value of num
used in num += xxx
is not the result of ++num
- it is the value we had before ++num
was executed.
So first iteration we have 0+=1
, second iteration it's 1+=2
and third iteration it's 3+=4
- that's 7
Upvotes: 6
Reputation: 131376
num++
increments num after
the instruction (it is a post-increment operator).
So num += num++;
assigns 0
to num
(num = 0 + 0 + 0).
After the instruction num += num++;
the post increment of num
(that is num++
) has no effect as num
was assigned to another value (that is num += 0
which the result is 0
) .
So num
is valued to 0
.
And so on for each iteration.
Replace num += num++
by ++num
that is the pre-increment operator, you will get the result : 3
(as you increment 1 by iteration).
Upvotes: 8