Path: utzoo!attcan!uunet!lll-winken!lll-tis!ames!mailrus!ukma!gatech!ncsuvx!ece-csc!harish From: harish@ece-csc.UUCP (Harish Hiriyannaiah) Newsgroups: comp.lang.c Subject: Re: Array indexing vs. pointers... Message-ID: <3777@ece-csc.UUCP> Date: 20 Sep 88 17:54:36 GMT References: <8809191521.AA17824@ucbvax.Berkeley.EDU> <68995@sun.uucp> Reply-To: harish@ece-csc.UUCP (Harish Hiriyannaiah) Organization: North Carolina State University, Raleigh, NC Lines: 44 In article <68995@sun.uucp> swilson@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@ece-csc.ncsu.edu {decvax,possibly other backbone sites}!mcnc!ece-csc!harish I am not, therefore I think not ?