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

# Arithmetic Expression Evaluation

Ranch Hand
Posts: 37
• Number of slices to send:
Optional 'thank-you' note:
Hello all,
consider:

int k=1;
int i = ++k + k++ + + k;
In PGJC (Programmer's Guide to Java Certification), they say that the above expression gets parsed as:
( (++k) + (k++) ) + (+k), thus yielding
( ( 2 ) + ( 2) ) + ( 3), i.e. 7
The precedence and associativity is trivial, but since postfix ++ has a higher precedence then prefix ++, shouldn't parameter evaluation result in the following parameterically evaluated expression:
( ( 3 ) + ( 1 ) ) + ( 3) ?
(which happens to be the same result in this case)

Ranch Hand
Posts: 1055
• Number of slices to send:
Optional 'thank-you' note:
Let's consider

int k=1;
int i = ++k + k++ + + k;

in more detail.
The RHS (right-hand-side) will evaluate from left to right, so we start with ++k. At this point:
RHS=2
k=2
that done, we move to k++
RHS= (2) + (2)
k=3
finally we go to + +k. The unary + does nothing.
RHS= (2) + (2) + (3)
k=3
so that i=7. Note that postfix and prefix operators are only "activated" when the thread of execution passes through them, and the value of k is not increased retroactively.
-anthony

Anthony Villanueva
Ranch Hand
Posts: 1055
• Number of slices to send:
Optional 'thank-you' note:
Personally, though, anybody who actually writes code this way should be quartered and hung.
-anthony

 It is an experimental device that will make my mind that most powerful force on earth! More powerful than this tiny ad! a bit of art, as a gift, the permaculture playing cards https://gardener-gift.com