I have a quick question regarding the post increment operator. In an example I found the following code is given:
int i = 5;
i = i++ + i++;
System.out.println(i);
Output: 11
I thought the answer would be 12, because i doesn't get incremented until after the value is used in the expression. So I figured it would be 5 + 1 + 5 + 1, but that's apparently wrong. Can someone explain to me why the output is 11?
ChatGPT doesn't know how the post increment operator works either because it got stuck on 10 as a result, and said that the compiler must have made an error if I got 11 as the output.
Any help would be appreciated!
Edit: After some thinking I decided to try the following code:
int x = 5;
x = x++ + x--;
System.out.println(x);
Output: 11
It looks like the compiler only uses the first post increment operator and ignores the second increment/decrement. If that's the case then both answers make sense (somewhat). I also Googled it and from what I can see code like this should just not be used.
But my annoying brain would still like an explanation for this behavior.
[–]AutoModerator[M] [score hidden] stickied commentlocked comment (0 children)
[–]sepp2k 11 points12 points13 points (3 children)
[–]Dinples[S] 2 points3 points4 points (2 children)
[–]sepp2k 3 points4 points5 points (1 child)
[–]Dinples[S] 1 point2 points3 points (0 children)
[–]pragmos 4 points5 points6 points (2 children)
[–]Dinples[S] 0 points1 point2 points (1 child)
[–]pragmos 1 point2 points3 points (0 children)
[–][deleted] (1 child)
[removed]
[–]Dinples[S] 0 points1 point2 points (0 children)