Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!watmath!clyde!cbatt!ihnp4!houxm!whuts!mhuxh!mhuxm!mhuxo!ulysses!allegra!princeton!rutgers!sri-spam!ames!ucbcad!ucbvax!cartan!brahms.Berkeley.EDU!ballou From: ballou@brahms.Berkeley.EDU.UUCP Newsgroups: comp.lang.c Subject: Re: induction variable optimization Message-ID: <878@cartan.Berkeley.EDU> Date: Mon, 2-Feb-87 17:09:00 EST Article-I.D.: cartan.878 Posted: Mon Feb 2 17:09:00 1987 Date-Received: Thu, 5-Feb-87 06:52:13 EST References: <182@ndmath.UUCP> Sender: daemon@cartan.Berkeley.EDU Reply-To: ballou@brahms.Berkeley.EDU (Kenneth R. Ballou) Organization: Math Dept. UC Berkeley Lines: 41 Keywords: does this work? In article <182@ndmath.UUCP> dean@ndmath.UUCP (Dean Alvis) writes: >In a recent Newsletter from Microsoft in Byte, the following is given as an >example of *induction variable optimization* : > > for(i=0;i<10;++i) j += i*7; > > evaluates to: > > for(i=0;i<70;i += 7) j += i; Well, not quite. If this is what the newsletter indicates, then the newsletter is in error. The idea is to avoid doing a multiplication by 7, and the correct idea is this: Replace for (i = 0; i < 10; ++ i) j += i * 7; with i = 10; for ($foo = 0; $foo < 70; $foo += 7) j += $foo; WHERE $foo is a compiler generated temporary whose lifetime is the for loop. (Aside: Please, no flames, I am quite well aware that '$' cannot appear in a C identifier!) This works as long as the compiler can prove that the value of i will not be altered by side effects in the loop. >Now, I may not understand what "evaluates to" means here, but it seems to me >that these statements are not equivalent, and following code which depends on >the value of i may not work correctly. Am I misunderstanding something? (Your "following code" appears to have turned into line eater fodder.) Yes, you are right, the code you indicated does not work. However, the suggested replacement does have the same effect. -------- Kenneth R. Ballou ARPA: ballou@brahms.berkeley.edu Department of Mathematics UUCP: ...!ucbvax!brahms!ballou University of California Berkeley, California 94720