Reputation:
Most binary arithmetic operators are left-associative in most programming languages. However, most compilers are free to evaluate the operands of a binary operator in either order. Are these statements contradictory? Why or why not?
EDIT
This comes from the book I am reading "Programming Language Pragmatics" Chapter 6, Exercise 6.1, I saw this book get a good recommendation on Steve Yegge's Blog. So I decided to check it out.
http://sites.google.com/site/steveyegge2/ten-challenges
Upvotes: 0
Views: 130
Reputation:
It turns out Associativity determines which subexpressions are arguments of which operators. It does not determine the order in which they are evaluated though.
For example left Associativity will determine that f(a) - g(b) - h(c) becomes (f(a) - g(a)) - h(c) but it doesn't determine whether f(a) will be evaluated before g(b).
Upvotes: 1
Reputation: 881553
Well, no, they're not contradictory, if only for the reason the sentences say "most" :-)
In either case, where the order of operations does not affect the result, the compiler should be free to choose the most efficient method. No matter how you slice and dice it, 7 * 2
is always equal to 2 * 7
.
Consider the statement:
a = (b + 1) * (c + 2)
The compiler can choose whether is uses:
(b + 1) * (c + 2)
(c + 2) * (b + 1)
or even:
(b * c) + b + b + c + 2
provided that the results are the same (within the expected bounds of accuracy).
In fact, provided the results are identical, even a statement like:
newval = 100 * PI * E / val * tot / 0.2
can have its individual components moved around without an issue. If the compiler can achieve the same ends with faster or smaller code, it should.
Language standards tend to specify that a certain result has to be reached, not how that result is reached.
Upvotes: 1
Reputation: 7736
What happens when you evaluate a binary operation in the reverse order?
Upvotes: 0