Order of precedence and associativity

E

Eric Sosman

In a * (b / c) I would expect the / to be evaluated first.

In a * b / c (that is, (a * b) / c) I would expect the * to be evaluated
first.

So precedence does affect the order in which the operations are done (if
not
the order that a,b,c are evaluated).

No, not even that much is sure. Furthermore, you *want*
this uncertain state of affairs! In `z = (x + y) * (x + y);' for
example, you *want* something like `z = x + y; z *= z;', which
means you *want* to discard one of the additions precedence and
associativity appear to demand.

Or, how about common sub-expressions? If the compiler sees
the same (side-effect free) sub-expression in several places, it
may well evaluate the sub-expression once and then use the pre-
calculated value instead of calculating it all over again. This,
clearly, does violence to an order-of-operation notion based solely
on the expression syntax.

Or, what about strength reduction? If the compiler replaces a
multiplication inside a loop with an addition, in what order does
the now-vanished multiplication occur with respect to the other
operands in its containing expression? Does it not-occur before
or after the other operations? ("Last night I met upon the stair /
A little man who wasn't there. / He wasn't there again today. /
I wish, I *wish* he'd go away!")

Precedence and associativity are syntactical rules (or, friendly
summaries thereof) that tell the compiler what kind of parse tree to
build from a sequence of operators and operands. Semantic rules then
dictate the effect of evaluating the expression described by the parse
tree. Finally, the compiler generates code -- pretty much any kind
of code -- to produce that effect. But the compiler has great freedom
in how it decides to produce the effect: It may replace multiplications
with additions or shifts, it may evaluate a sub-expression long before
it seems to appear, it may intermix the evaluation of expressions in
separate statements, and so on. As long as it produces the required
outcome (including all observable side-effects in their proper order),
anything goes.
 
D

David Thompson

On Tue, 15 Jun 2010 10:12:18 -0400, Eric Sosman
Some C implementations (most, even, but not all) distinguish
between "plus zero" and "minus zero." <snip rest>

*for floating-point* most do. C also *allows* negative-zero for
integer types using 1s'-complement or sign&magnitude, but practically
no machines (and thus C implementations) today do so.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,143
Latest member
SterlingLa
Top