This week's giveaway is in the Java/Jakarta EE forum.We're giving away four copies of Java EE 8 High Performance and have Romain Manni-Bucau on-line!See welcome thread
Win a copy of Java EE 8 High Performance this week in the Java/Jakarta EE forum!
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Pre and Post increment problem

Greenhorn
Posts: 8
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?

Ranch Hand
Posts: 207
3
• X 2
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).

Marshal
Posts: 5388
374
Have a cow, O Shea, answer seem to be correct

O Shea
Ranch Hand
Posts: 207
3

Liutauras Vilda wrote:Have a cow, O Shea, answer seem to be correct

Thank you very much