() ignored in some expressions

Richard Tobin richard at aiai.ed.ac.uk
Wed Apr 11 06:37:25 AEST 1990


In article <18833 at duke.cs.duke.edu> drh at duke.cs.edu writes:
> I often what to do things like increase an integer by 50%.  This can
> be done as follows:    i = (i*3)/2;   If an optimizing compiler can
> ignore the parenthesis, then it will probably notice that it can evaluate
> 3/2 at compile time to 1.  It will then notice that a multiplication by
> 1 can be ignored.  The end result is that my optimizing compiler will
> decide not to generate any code at all for the above statement.
> 
> According to K&R, the only way to avoid this disaster is to code the
> operation in two steps:   i *= 3; i /= 2;

This is just not true.  K&R1 says this (page 37):

  The order of evaluation is not specified for associative and
  commutative operators like * and +; the compiler may rearrange
  a parenthesized computation involving one of these.

If this is the passage in K&R you were thinking of, note that it refers
to a "computation involving *one* of these".

The only case where parentheses are inadequate in such a computation is
when an intermediate result might overflow or (in the case of floating
point) lose precision.  For example, a K&R compiler might rearrange

            100000 * (100000 / 10000)

in such a way that integer overflow would occur on a machine with
32 bit integers.  This problem does not arise in ANSI C, where 
expressions may be rearranged only if it doesn't change the result.
On a machine which doesn't detect integer overflow, the result will
always be unchanged if the only operators are integer + and -.

-- Richard
-- 
Richard Tobin,                       JANET: R.Tobin at uk.ac.ed             
AI Applications Institute,           ARPA:  R.Tobin%uk.ac.ed at nsfnet-relay.ac.uk
Edinburgh University.                UUCP:  ...!ukc!ed.ac.uk!R.Tobin



More information about the Comp.lang.c mailing list