views:

51

answers:

3

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

A: 

What happens when you evaluate a binary operation in the reverse order?

eruciform
+1  A: 

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.

paxdiablo
i hope he doesn't cut-and paste this for homework. :-P
eruciform
*"`pct = 100 * val / tot` can have its individual components moved around..."* - not if / is integer division :)
BlueRaja - Danny Pflughoeft
@eruciform, the homework tag was added later and by somebody else (I prefer to ask first but I understand those who don't). There's been ample cases on SO where things that look like homework turn out to be self-education and, honestly, if someone wants to cheat, that's their issue - they'll likely never be a serious contender for my job, or, indeed, _anyone_ who's competent. And, if they think their educators don't monitor sites like this, they're in for a rude shock when they get their assignments back :-)
paxdiablo
@BlueRaja, I think I covered that with the phrase "provided that the results are the same", but I'll clarify for you.
paxdiablo
@paxdiablo: yeah, i know, it's always a balance. just stating a concern on my part. and i also monitor this site for my own courses. haven't caught someone improperly using this site yet, but give it time. ;-P
eruciform
+1  A: 

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).