induction variable optimization

ballou at brahms.Berkeley.EDU.UUCP ballou at brahms.Berkeley.EDU.UUCP
Tue Feb 3 08:09:00 AEST 1987


In article <182 at ndmath.UUCP> dean at 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 at brahms.berkeley.edu
Department of Mathematics		UUCP:  ...!ucbvax!brahms!ballou
University of California
Berkeley, California  94720



More information about the Comp.lang.c mailing list