Yet Another Silly Question

Chris Torek chris at mimsy.UUCP
Wed Jun 7 14:59:37 AEST 1989


[context:	int a[MAX], *p; for (p = &a[0]; p < &a[MAX]; p++) ...]

In article <18229 at unix.cis.pittsburgh.edu> jcbst3 at unix.cis.pittsburgh.edu
(James C. Benz) writes:
>The machine still has to dereference &a[MAX] on each iteration of the
>loop, doesn't it?  It has to perform the test on each iteration to see
>if p is < &a[MAX], and unless the optimizer is really on top of things,
>it has no way of generating the comparison address as a constant.

No: on a typical machine, with a stack pointer (and without alloca(),
or with a frame pointer and optionally with alloca()), the `for' loop
generates code of the form:

		lea	sp@(-8),a2	| compute &a[MAX]
		lea	sp@(-100),a3	| p = &a[0];
	loop:	cmp	a3,a2		| p < [constant]
		jcc	out		| no, exit loop
		...
		jbr	loop
	out:

`a' is not a modifiable lvalue (although it is not `constant', since
the array is local to some function), and MAX is a constant, so &a[MAX]
cannot change during any iteration of the loop.

Actually, many machines have a `count down to zero' loop form which
may be still more efficient, and an optimising compiler (such as
`gcc -O -fstrength-reduce') may change the loop to

	for (p = &a[0], temp = sizeof a/sizeof *a; --temp >= 0; p++)
		... use *p ...

which contains both a strength reduction and a variable substitution
over the original

	for (i = 0; i < MAX; i++) ... use a[i] ...

but does require that `i' not be used for anything except the subscript
calculation.
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain:	chris at mimsy.umd.edu	Path:	uunet!mimsy!chris



More information about the Comp.lang.c mailing list