Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!uunet!mcsun!ukc!edcastle!aiai!richard From: richard@aiai.ed.ac.uk (Richard Tobin) Newsgroups: comp.lang.c Subject: Re: () ignored in some expressions Message-ID: <2194@skye.ed.ac.uk> Date: 10 Apr 90 20:37:25 GMT References: <48079@lanl.gov> <101287@convex.convex.com> <18833@duke.cs.duke.edu> Reply-To: richard@aiai.UUCP (Richard Tobin) Organization: AIAI, University of Edinburgh, Scotland Lines: 37 In article <18833@duke.cs.duke.edu> drh@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@uk.ac.ed AI Applications Institute, ARPA: R.Tobin%uk.ac.ed@nsfnet-relay.ac.uk Edinburgh University. UUCP: ...!ukc!ed.ac.uk!R.Tobin