This week's book giveaway is in the Performance forum.
We're giving away four copies of The Java Performance Companion and have Charlie Hunt, Monica Beckwith, Poonam Parhar, & Bengt Rutisson on-line!
See this thread for details.
Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Postfix operation

 
Vidyavathi saravanan
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


This is one of Dans' question. The answer is 5 as per ( a=1+2+2).
My doubt is what happened to the postfix operation a++. ( Is it not correct that this postfix makes a as 6.
 
Chris Allen
Ranch Hand
Posts: 127
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Vidyavathi saravanan:


This is one of Dans' question. The answer is 5 as per ( a=1+2+2).
My doubt is what happened to the postfix operation a++. ( Is it not correct that this postfix makes a as 6.


The way I got to the answer was as follows:
int a=1;a += ++a + a++;
then: a += (2) + a++;
then: a += (2) + (2); ->a will be incremented to 3 once the statement is finished
then: 1 += (2) + (2);
equals: a=5 (assign 5 to the value of a)

Remember that the postfix operator only takes effect AFTER the statement is processed and as such, is not involved in the calculation of this line. Since the value of a has already been set to 5, the effect is that the value of a is incrmented but it is not assigned to a and basically is lost.

Think of it this way:
We have already assigned the value of the variable a so you can increment it, but it will be ignored as the assignment is already done.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What actually happens is the following:

a += ++a + a++; (a==1)
a = a + ++a + a++; (a==1)
a = 1 + ++a + a++; (a==1)
a = 1 + a + a++; (a==2)
a = 1 + 2 + a++; (a==2)
a = 3 + a++; (a==2)
a = 3 + 2 [need to increment a now]; (a==2)
a = 3 + 2; (a==3)
a = 5; (a==3)
(a==5)

That is, a does get incremented, but before the assignment of the expressions value happens.

Does that help?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic