• Post Reply Bookmark Topic Watch Topic
  • New Topic

Pre and Post increment problem  RSS feed

 
Nicole Strawn
Greenhorn
Posts: 8
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Another beginner question:



Which gives:
11
10

In prefix form I'd get 11 for both because the ++ would happen first before y was assigned the value of 11, so print(y) would be 11.
But in post form, the increment happens after the expression, which in this case would be the assignment expression to give y the value, so y gets the value of x before x is incremented, but then, print(x) gives 11. print(x) is always 11, x is incremented either way...

But why is print(y) giving 10?

If the line above gives 11, print(y) below doesn't reassess y at that point in the same way that x gives 11?

At no point does y become X++? Is there a rule that you should use the prefix form is you want it to count and the post form if you don't want it to count? "Post increment for post assignment" (since the original value gets assigned and then gets incremented afterwards?) Is that a good enough understanding to work with and move on?

Can someone tell me, please, what's going over my head?

 
O Shea
Ranch Hand
Posts: 196
3
Java MySQL Database Oracle
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Post increment operators, means first assign and then increment.
So int y=x++; // this line first assign the value of x to y(so y becomes 10 and x is 10), now once value is assigned, after that, the value of x is incremented(hence y is still 10, but x becomes 11).
 
Liutauras Vilda
Sheriff
Posts: 4926
334
BSD
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Have a cow, O Shea, answer seem to be correct
 
O Shea
Ranch Hand
Posts: 196
3
Java MySQL Database Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Liutauras Vilda wrote:Have a cow, O Shea, answer seem to be correct


Thank you very much
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!