Yet Another Silly Question

Karl Heuer karl at haddock.ima.isc.com
Wed Jun 7 04:28:37 AEST 1989


In article <18229 at unix.cis.pittsburgh.edu> jcbst3 at unix.cis.pittsburgh.edu (James C. Benz) writes:
>[someone writes about the loop: for (p=&a[0]; p<&a[MAX]; ++p) ...]
>The machine still has to dereference &a[MAX] on each iteration of the loop,
>doesn't it?

There's no dereference involved.  It does have to *evaluate* &a[MAX].

>unless the optimizer is really on top of things, it has no way of generating
>the comparison address as a constant.  It really has no way of knowing that
>&a[MAX] won't change during the course of the program, so it must be
>re-computed on each iteration of the loop.

The value "&a[MAX]" cannot change during the scope of the identifier "a".  On
a VAX-like architecture, the array a (which has block scope and auto storage
duration) is commonly implemented as a constant offset from a frame pointer;
the additional offset MAX*sizeof(int) will be absorbed by constant folding.
The only non-obvious optimization is to keep the value &a[MAX] in a register.

>In any situation I hope to encounter in the kind of work I do, (database
>admin) I will trade off the readability of the first example against the run
>time efficiency of the second, and choose readability every time.

I don't necessarily agree that pointers are less understandable than indexing,
but I agree that readability/maintainability should be the first concern.

Karl W. Z. Heuer (ima!haddock!karl or karl at haddock.isc.com), The Walking Lint



More information about the Comp.lang.c mailing list