Path: utzoo!attcan!uunet!seismo!sundc!pitstop!sun!thetone!swilson From: swilson%thetone@Sun.COM (Scott Wilson) Newsgroups: comp.lang.c Subject: Re: Array indexing vs. pointers... Message-ID: <68995@sun.uucp> Date: 19 Sep 88 22:55:03 GMT References: <8809191521.AA17824@ucbvax.Berkeley.EDU> Sender: news@sun.uucp Reply-To: swilson@sun.UUCP (Scott Wilson) Organization: Sun Microsystems, Mountain View Lines: 34 In article <8809191521.AA17824@ucbvax.Berkeley.EDU> U23405@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@sun.com Sun Microsystems uucp: ...!sun!swilson Mt. View, CA