a style question

Karl Heuer karl at haddock.ima.isc.com
Tue Oct 2 13:46:37 AEST 1990


In article <1990Oct1.174941.22195 at zoo.toronto.edu> henry at zoo.toronto.edu (Henry Spencer) writes:
>What *can* make a difference is to run the loop backwards, algorithm
>permitting:
>	for (x = 99; x >= 0; x--)

In keeping with the idea that x is ranging through the half-open interval
[0,100) rather than the closed interval [0,99], I often write this as
	for (x = 100; --x >= 0;)
instead.  (Possibly more efficient, too, since the decrement and the test are
not separated by a basic-block-boundary, and hence the test instruction can be
omitted on vaxlike architectures.)

Note that with either Henry's example or mine you will lose big if x is an
unsigned integer (and if you don't use lint to catch it).  I usually use
	for (x = 100; x != 0; --x)
on unsigned countdown loops where the index doesn't matter (i.e. just "do 100
times"); if you actually need the interval [0,100),
	for (x = 100; x-- != 0;)
does the job (though probably less efficiently).

Karl W. Z. Heuer (karl at kelp.ima.isc.com or ima!kelp!karl), The Walking Lint



More information about the Comp.lang.c mailing list