home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!usc!rpi!bu.edu!dartvax!news
- From: davidg@polvadera.dartmouth.edu (David Gelhar)
- Newsgroups: comp.lang.c
- Subject: Re: Order of evaluation
- Message-ID: <1992Nov9.065342.20862@dartvax.dartmouth.edu>
- Date: 9 Nov 92 06:53:42 GMT
- References: <qBak-G@ppcger.ppc.sub.org>
- Sender: news@dartvax.dartmouth.edu (The News Manager)
- Organization: Dartmouth College, Hanover, NH
- Lines: 55
-
- In article <qBak-G@ppcger.ppc.sub.org> writes:
-
- >
- > Let's take a look at Section A7.6:
- >
- > A7.6 Multiplicative operators
- >
- > The multiplicative operators *, /, and % group left to right.
- > [ ... ]
- >
- > So the world seems to be OK. But look at Section A7:
- >
- > A7 Expressions
- >
- > [ ... ]
- > The precedence and associativity of operands is fully specified, but
- > the order of evaluation of expressions is, with certain exceptions,
- > ^^^^^^^^^^^^^^^^^^^
- > undefined, even if the subexpressions involve side effects. That is,
- > unless the definition of an operator guarantees that its operands are
- > evaluated in a particular order, the implementation is free to evaluate
- > operands in any order, or even to interleave their evaluation. [ ... ]
- > This rule revokes the previous freedom to reorder expressions with
- > operators that are mathematically commutative and associative, but
- > can fail to be computationally associative. [ ... ]
- >
- > So the compiler seems to be allowed to evaluate
- >
- > a * ( b * c ) instead of a * b * c
- >
- > but not
- >
- > a * ( b / c ) instead of a * b / c
- >
- > Is this correct?
- >
-
- No. The point to remember is that precedence/associativity are NOT the
- same thing as order of evaluation. The expression "a * b * c" is required
- to be treated like "(a * b) * c", that is, "a" and "b" are multiplied together
- and the result is multiplied by "c"; that's the associativity rule. As it
- says above, "the precedence and associativity of operands is fully specified".
- In other words, the parsing of the expression (what operands go with what
- operators) is precisely defined: the operands of the rightmost "*" in this
- example are "a*b" and "c". What's undefined is the order of evaluation --
- the subexpressions "a", "b" and "c" are not required to be evaluated in any
- particular order.
-
- The only time order of evaluation matters (indeed, the only time you can
- even _tell_ what order is being used, without resorting to looking at
- object code) is when the subexpressions have side effects. For example,
- in "a() * b() * c()" there's no telling what order the functions may be
- called in. This is fine if the functions have no side effects, but if
- they do (for example, if they print the function name on the terminal
- when called) the results are undefined.
-