Help coderanch get a
new server
by contributing to the fundraiser
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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Jeanne Boyarsky
• Ron McLeod
• Paul Clapham
• Liutauras Vilda
Sheriffs:
• paul wheaton
• Rob Spoor
• Devaka Cooray
Saloon Keepers:
• Stephan van Hulst
• Tim Holloway
• Carey Brown
• Frits Walraven
• Tim Moores
Bartenders:
• Mikalai Zaikin

# post increment opeartor

Ranch Hand
Posts: 39
• Number of slices to send:
Optional 'thank-you' note:
double x=4.5;
System.out.println(x+ ++x);

It prints 10.0
why not 5.5 + 5.5 = 11.0???

Ranch Hand
Posts: 664
• Number of slices to send:
Optional 'thank-you' note:
It's very simple.
The value of x is 4.5
And then you are incrementing the value (++x) ie.5.5
so you 'll get the value (4.5+5.5) which is 10.

In Post Increment Operator, the value is first assigned and then Incremented.
But if there is another variable after it ,then it uses the Incremenented value.

Check this code and see if it makes things clearer.

Some one correct me if I am wrong.

[ March 12, 2008: Message edited by: Nabila Mohammad ]
[ March 12, 2008: Message edited by: Nabila Mohammad ]

Ranch Hand
Posts: 128
• Number of slices to send:
Optional 'thank-you' note:
My explanation would be:
arithmetic expressions are evaluated from left to right. Or, to be more precise (for two-argument operators, such as +): left subtree first, then right subtree.
In the expression "x + ++x" we have:

which means: to count the value of the sum we count the left subtree first, which is "x". "x" is equal to 4.5.
Then we count the value of the right subtree. There we have a preincrement operator "++" with argument "x". So we take the value of "x" = 4.5, increment it by one = 5.5 and return it as a result of the right subtree of the "+" operator. Then we calculate the sum, which is 4.5 + 5.5 = 10.

Ranch Hand
Posts: 30
• Number of slices to send:
Optional 'thank-you' note:
thank you..
this is the best way to solve this kind of questions. this way one can never go wrong. i always become confused with this kind of questions. thanks again.

 The problems of the world fade way as you eat a piece of pie. This tiny ad has never known problems: We need your help - Coderanch server fundraiser https://coderanch.com/t/782867/Coderanch-server-fundraiser