Array indexing vs. pointers...

Harish Hiriyannaiah harish at ece-csc.UUCP
Wed Sep 21 03:54:36 AEST 1988


In article <68995 at sun.uucp> swilson at sun.UUCP (Scott Wilson) writes:
->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).

All this is really fine if

1. The processor has autoincrement addressing (any decent processor should
   have it. )

2. The compiler generates the code for the same. 

   #2 does not always happen. So, it is best to see the assembler output
before deciding on the indexing strategy. Also, in some processors,indexing
will mean concatenation of the index to the higher order bits of the
address. In this case, indexing might turn out to be faster than indirect
addressing.

-- 
harish pu. hi.     harish at ece-csc.ncsu.edu
                   {decvax,possibly other backbone sites}!mcnc!ece-csc!harish

I am not, therefore I think not ?



More information about the Comp.lang.c mailing list