Another silly question

Tim Olson tim at crackle.amd.com
Tue May 23 02:33:02 AEST 1989


In article <756 at mccc.UUCP> pjh at mccc.UUCP (Pete Holsberg) writes:
| In article <17635 at mimsy.UUCP> chris at mimsy.UUCP (Chris Torek) writes:
| =In article <749 at mccc.UUCP> pjh at mccc.UUCP (Pete Holsberg) writes:
| =[in response to article <607 at kl-cs.UUCP> by pc at cs.keele.ac.uk (Phil Cornes)]
| =>Can you explain why compilers produce different code for "a[i]" and "*(a+i)"?
| =
| =I have never observed one to do so.  There is no reason for a compiler
| =to generate different code, as the expressions are semantically identical.
| 
| Perhaps I've asked the wrong question.  I saw a couple of simple test
| programs that assigned 0 to each member of an array.  One used array
| subscript notation, and the other, pointer notation.  I compiled these
| on a 7300, a 3B2/400, and a 386 running Microport V/386, using a variety
| of compilers (cc and gnu-cc on the 7300, fpcc on the 3B2, and cc and
| Greenhills on the 386).  I ran each version and timed the execution. 
| The subscript versions had different run times from the pointer versions
| (some slower, some faster!).  I assumed - perhaps naively - that the
| differences were caused by differences in code produced by the different
| compilers (and of course the hardware differences).  Was that wrong? 
| How does one account for the differences?

If you wrote the routines like:

	
	int a[MAX];			int a[MAX];
	int i;				int i;
	for (i=0; i<MAX; ++i)		for (i=0; i<MAX; ++i)
		a[i] = 0;			*(a+i) = 0;

Then the code generated should probably be identical (and it was, on the
three machines I tried it on).  However, if instead you wrote them like:

	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;

Then you indeed might get different assembly language generated.  The
second pointer version has had a "loop induction" optimization performed
by hand. 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.


	-- Tim Olson
	Advanced Micro Devices
	(tim at amd.com)



More information about the Comp.lang.c mailing list