3

Possible Duplicate:
What are the rules for evaluation order in Java?

a = f(b) * - d + e++ + f(e)

Just curious how this would go about evaluating step by step and where could I find the rules for doing so?

Community
  • 1
  • 1
Tom V
  • 79
  • 5

1 Answers1

2

SECOND EDIT: My answer is apparently wrong, see the link Adam Liss provided in the comments to the question (has now been moved to the question itself, see "possible duplicate"). I'm leaving my answer here for the details Niklas provided, along with my (incorrect) answer to see what sparked the comments.


If I'm not mistaken, the evaluation tree is built according to the order of operator precedence and then evaluated accordingly. Method calls should be the very first thing to evaluate though, since the return values may be required in the expression.

EDIT: evaluation (assuming sums really are evaluated left-to-right) would look like this (the "intermediate value" called t is what the current value after each step is):

evaluate f(b)
calculate t = f(b) - d
calculate t = t + e      (since it's e++ and not ++e)
evaluate e++
evaluate f(e)
calculate t = t + f(e)
assignment a = t
G. Bach
  • 3,869
  • 2
  • 25
  • 46
  • Where are function calls located in that link for precedence? – Tom V Mar 28 '12 at 02:22
  • the subexpressions are evaluated left to right, regardless of operator precedence (or associativity). So `e++` will be evaluated before `f(e)`, for example. [Quick demo](http://ideone.com/UB8X8). – Niklas B. Mar 28 '12 at 02:22
  • Method calls aren't linked there; they have return values and as such should be evaluated as a variable would be. – G. Bach Mar 28 '12 at 02:32
  • Where does the multiplication get done in your example Niklas? – Tom V Mar 28 '12 at 02:37
  • @Niklas: I don't fully understand; the order of precedence of operators determines what is considered the smallest possibly subexpression, which is where evaluation must start, no? – G. Bach Mar 28 '12 at 02:38
  • @G. Bach: Yes, I meant *independent* subexpressions like `f(b)`, `-d`, `e++` and `f(e)` in the example. Operator precedence is not enough to determine in which order those should be evaluated. Some languages leave the order undefined (C/C++), Java and C# have the left-to-right rule. It doesn't have anything to do with "sums are evaluated left-to-right". Everything is. More information can be found in the expert answer of the linked question. – Niklas B. Mar 28 '12 at 02:43
  • @Tom V: Nowhere, it was just an example to demonstrate that method calls aren't necessarily evaluated first. – Niklas B. Mar 28 '12 at 02:49