programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source 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?

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

Sheriff
Posts: 5684
393
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

 Have you no shame? Have you no decency? Have you no tiny ad? Rocket Oven Kickstarter - from the trailboss https://coderanch.com/t/695773/Rocket-Oven-Kickstarter-trailboss