• Post Reply Bookmark Topic Watch Topic
  • New Topic

Postfix ++ operator problem.  RSS feed

 
Jean Fore
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a question related to the postfix increment / decriment operator.
I have something like this in a program.
long i = 10;
long k = i++ + i--;
System.out.println("k = "+k);
System.out.println("i = "+i);
Here, the resul is k = 21 and i = 10.
But I believe that k should be getting a result of addition between the old values of "i" twice. So k should be 10 + 10 since postfix operator works only after the resulting value is assigned on the left side. Can anyone help me with the explanation please?

Thanks
JEAN
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The increment and decrement have equal priority so the first expression evaluated is i++. Its value is 10, but the increment changes i to 11. When you evaluate i--, the value is 11.
 
Jean Fore
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the immediate response. But I am still confused about the value of "k". My belief is any postfix operator should be doing it's operation only with the old value and assign that result value to the result variable on the left hand side and THEN the postfix operation will take place.
So according to my conviction,
long k = i++ + i--;
will work as long k = (10)++ + (10)--;
-> k = 20. after k gets it's value, i++ will happen, which will result 11 and then i-- will happen, which will result in 10 back again. So when you complete that line of code, k should be 20 and i should be 10. what do you say? I am sorry for bothering you again.
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's no bother. The entire right-hand side is going to be evaluated before anything is stored in the left-hand side.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's a common misconception that the increment/decrement happens after the assignment. The truth is that it happens immediately, but the expressions value is the old value of the variable.

So

k = i++ + i--;

executes as follows:

k = i++ + i--; (i==10)
k = 10 + i--; (i==11)
k = 10 + 11; (i == 10)
k = 21; (i == 10)
 
Jean Fore
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you so much Keith and Ilja. Now I understand exactly how this works. I was searching for this explanation for so long. Thank you again.
-JEAN.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!