Yet Another Silly Question
Tim Olson
tim at crackle.amd.com
Wed Jun 7 02:42:48 AEST 1989
In article <18229 at unix.cis.pittsburgh.edu> jcbst3 at unix.cis.pittsburgh.edu (James C. Benz) writes:
| In article <2550091 at hpisod2.HP.COM] decot at hpisod2.HP.COM (Dave Decot) writes:
| ]] int a[MAX]; int a[MAX];
| ]] int i; int *p;
| ]] for (i=0; i<MAX; ++i) for (p=&a[0]; p<&a[MAX]; ++p)
| ]] a[i] = 0; *p=0;
| ]]
| ]] ...
| ]]
| ]] ... On some compiler/machine combinations, this will run faster,
| ]] because the scaling operation and base/offset addition have been
| ]] eliminated; on others it may run slower, because a specific addressing
| ]] mode cannot be used.
| ]
| ]Note that the scaling operation has not necessarily been completely
| ]eliminated; it may have become hidden in "++p" because increments by 1
| ]may be much faster than increments by sizeof(*p).
| ]
| Also, the scaling operation has simply been moved to the "for" line, as
| far as I can tell.
Actually, the "scaling operation" has been strength-reduced from a shift
or multiply in the inner-loop to a constant add (which was already
required to increment the variable "i").
| The machine still has to dereference &a[MAX] on each
| iteration of the loop, doesn't it?
No. The address of a[MAX] is compared with the current pointer without
referencing the value at a[MAX].
| 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. 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.
Not so in this example -- the array "a" is declared as "int a[MAX]", so
the compiler knows that "a" is a constant lvalue which can never change.
However, if "a" were actually a pointer, you are correct -- the value of
"&a[MAX]" could potentially change if the value of "a" is changed in the
loop.
-- Tim Olson
Advanced Micro Devices
(tim at amd.com)
More information about the Comp.lang.c
mailing list