Jesper de Jong wrote:. . . an expression such as 2 + 3 * 4 means 2 + (3 * 4) = 14 and not (2 + 3) * 4 = 20.
But it is
not evaluated like this:-
1: The * has a higher precedence so work out 3*4. That's 12.2: Add 2. That makes 14.No, because that is not (as Jesper said) left‑to‑right. It is evaluated like this:-
1: Start with 2.2: That has a + to its right, so add something.3: That something has a * in which has a higher precedence, so calculate that as 124: Add 12: that makes 14.You might get the same answer but that is only by luck. The second time round I did evaluate the arithmetic left‑to‑right.
In
Java Puzzlers by Bloch and Gafter, they ask what this expression does:-
i ^= j ^= i ^= j; (or similar).
Now that is repeated bitwise exclusive‑OR‑ing the two numbers. So I got myself some paper and worked out that it would swap the values of the two
ints (it cannot work for floating‑point numbers.) And I wrote myself the following little program
And this is its output. It works beautifully, because C does not have a left‑to‑right rule.
campbell@campbellsComputer:~/CPrograms$ ./swap 123 456
i = 123 j = 456. Later, i = 456 j = 123
Now try it in Java®
campbell@campbellsComputer:~/CPrograms$ java IntSwap 123 456
i = 123 j = 456. Later, i = ??? j = ???
You will have to run it yourself to see the output
The difference is because the handling of multiple assignments (what horrible code) falls foul of the left‑to‑right rule.
By the way: you may be given that very same expression in an interview question. You now know the right answer.