Tricky construction (i += i++)

Ranch Hand
Posts: 56
Hi, guys! Could someone, please, explain me why this code:

will show "0" as a result? I supposed it'll show "1"

And question number two: one guy told me that operation of post-increment (i++) executes slower than (++i), because the first one demands a creation of temporary variabe. I found this old topic, but they were talking about C++ and there were few opposite points of view, so I didn't get whether it is true or not. Could you please clear things up for me?

Stephan van Hulst
Bartender
Posts: 6479
83
• 1
i += i++
(i += (i++))
(0 += (i++))
(0 += (0++))
(0 += 0)
0

Technically it's very possible that i++ executes slightly slower than ++i. The difference however will be so incredibly small that you don't need to worry about it. Just use the correct statement for the correct situation.

Ranch Hand
Posts: 56
Stephan van Hulst wrote:i += i++
(i += (i++))
(0 += (i++))
(0 += (0++))
(0 += 0)
0

But what's happening to i++ operation? I thought it should've incremented 0 after assignment...I can't get why it's not happening Could you please explain more in details?

Matthew Brown
Bartender
Posts: 4568
9
• 1
But what's happening to i++ operation? I thought it should've incremented 0 after assignment

It would have been incremented. But the expression is evaluated left-to-right. And the effect of that is that the initial value of i has effectively been saved before it's incremented. So the final assignment just stamps over the top of that increment.

Here's an alternative way of stepping through it that might demonstrate.

I'd recommend never actually doing things like this - don't mix increment operators and assignment. As you can see, it can rapidly lead to confusion.

Ranch Hand
Posts: 56
Now I get it! Thank you, guys! Appreciate it

Campbell Ritchie
Sheriff
Posts: 50675
83
• 1
Well done, searching , but you were unlucky with what you found, even allowing for its being 7 years old. C++ is a different language, and the behaviour of different operators is different. For example, in C, that expression is not strictly defined at all, and getting an output of 1 or 0 is possible. Both values are permitted by the C language. But not in Java, which has stricter specifications. We have an FAQ, and there is something in the Java Tutorials, but the Java Language Specification is by no means easy to understand.

shivamahesh bachu
Greenhorn
Posts: 13
i = 0;
i += i++;
i = i + i++;
i = 0 + 0

Thanks.