Array indexing vs. pointers...
Scott Wilson
swilson%thetone at Sun.COM
Tue Sep 20 08:55:03 AEST 1988
In article <8809191521.AA17824 at ucbvax.Berkeley.EDU> U23405 at UICVM (Michael J. Steiner) writes:
>First, I have a question. How and why is array indexing slower than
>pointer arithmetic? They are very similar. Also, I think that compilers
>should automatically translate array indexing into pointer arithmetic when
>dealing with arrays in C. Any comments, opinions?
In K&R pg. 186 it says: "E1[E2] is identical (by definition) to
*((E1)+(E2))." So array indexing is exactly the same as pointer
arithmetic. What you might be hearing is about the efficiency of using
array indexing in loops versus using pointers. For example:
int i, sum = 0, array[100];
for (i = 0; i < 100; i++)
sum += array[i];
is less efficient than:
int i, sum = 0, array[100], *ip = array;
for (i = 0; i < 100; i++, ip++)
sum += *ip;
In the first case, using array[i] results in a shift and an add
to compute the address of the array element. (If the array element
size was not a power of two then a multiplication would be needed.)
In the second we are just bumping a pointer up each time through
the loop. There is more that can be done to the second example
as well (why increment two vars side-by-side).
--
Scott Wilson arpa: swilson at sun.com
Sun Microsystems uucp: ...!sun!swilson
Mt. View, CA
More information about the Comp.lang.c
mailing list