>
> On 11/07/2011 05:02 AM, HankyPanky wrote:
> > ...I remember that I wrote an expression parser for evaluating
> > simple mathematical expressions such as 2 + 3 * 4 - 5 etc.
> >
> > Back then, parenthesis not only changed the precedence but also the
> > order of evaluation. I mean writing an expression like 2 * (30 - 5)
> > forced my implementation (stack-based) to first evaluate 30 - 5 to 25
> > followed by a multiplication which yielded 50. On the other hand,
> > without parentheses first 2 * 30 got evaluated to 60 followed by a
> > subtraction which in turn yielded 55. Can you put all these together
> > and make it even clearer for me? I mean, does this challenge your last
> > sentence which goes: Simply put, precedence has nothing to do with
> > order of evaluation?
>

On Thu, Nov 10, 2011 at 9:47 AM, Patrick Horgan <[email protected]> wrote:

> In most languages this would still not change the order of evaluation.

Multiply is evaluated left to right.  First we evaluate the left side
> and get 2.  Then we evaluate the right side and get 25, then we can do
> the multiply.  It's still left to right.
>
> Of course since multiply doesn't do short circuit evaluation you don't
> notice that the two gets evaluated first, because the right side will
> still get evaluated before the operator* is applied.


Here is a JavaScript test that demonstrates what you're saying. You can run
it here:

http://jsfiddle.net/geary/m5bUS/

Or paste the code into your favorite JavaScript debugger console:

// Trace the order of execution of arithmetic operations.

// The value() function simply returns the value it was
// passed, and logs that value in an array. When done,
// we alert the array contents, showing the order of
// the value() calls.

var values = [];

function value( v ) {
    values.push( v );
    return v;
}

value( value(2) * ( value(3) + value(4) ) );

alert( values.join('\n') );

In this test case, the alert shows:

2
3
4
14

Of course the code can easily be modified to try out other expressions.

-Mike

-- 
To view archived discussions from the original JSMentors Mailman list: 
http://www.mail-archive.com/[email protected]/

To search via a non-Google archive, visit here: 
http://www.mail-archive.com/[email protected]/

To unsubscribe from this group, send email to
[email protected]

Reply via email to