Get Time
Search | Watch Thread  |  My Post History  |  My Watches  |  User Settings
View: Flat (oldest first)  | Threaded  | Tree
Previous Thread  |  Next Thread
Re: Order of Operations (response to post by sbeitzel) | Reply
You are absolutely right1
In C / C++ the expression x+y-z may be evaluated e.g. like this (assuming that x,y,z may themselves be complicted expressions):
compute T1 := x
compute T2 := y
compute T3 := T1+T2
compute T4 := z
compute T5 := T3-T4

or maybe like this
compute T1 := z
compute T2 := y
compute T3 := x
compute T4 := T3+T2
compute T5 := T4-T1

or many other ways, but always with the addition performed before the substraction. I.e., the evaluation order of subexpressions is not specified (implementaion dependant, subject to optimization etc.), but operator precedence and associativity fully dictate the order of operations, so that x+y-z is always interpreted as ((x+y)-z) -- in fact on purpose because of rounding problems (i.e. because floating point addition is not associative) but that's not the only reason: even though int addition is associative, I might overload '+' in a way that is not even theoretically associative.

Strictly speaking, I'm not sure whether some compilers might in fact make at least use of comuutativity and rewrite x+y-z as ((y+x)-z). It's hard to tell anyway as one might simply reinterprete assembler instructions differently (is ADD eax,edx "let edx=eax+edx" or "let edx=edx+eax"?)
Order of Operations | Reply
As an example, the expression x + y - z may once be evaluated as x + (y - z) and the other time as (x + y) - z. Try substituting the values x = 1.0 and y = z = 1030.

I would be very wary of doing any math in a language that doesn't enforce order of operations. While it's true that addition and subtraction have equal precedence, order is then supposed to go from left to right. If a compiler feels free to reorder the operands, then the compiler is broken.