a style question

Stephen Clamage steve at taumet.com
Mon Oct 1 09:33:05 AEST 1990


aryeh at cash.uucp (the over worked C something or another) writes:

>Since I going to be doing my first team effort I want to know if this is bad 
>style:
>	for(x=0;x!=100;x++) ...

In his book "C Traps and Pitfalls", Andy Koenig recommends using
asymmetric bounds.  In this particular example, there are 101
iterations, while the casual reader might read it as 100.  If you
write instead
	for(x=0; x < 101; x++) ...
where the lower bound is INclusive and the upper bound is EXclusive,
it makes it very obvious what is going on.  Furthermore, such loops
are often used to address arrays.  Writing the bounds this way nicely
parallels the array declaration
	T ray[101];
where ray has 101 elements from 0 up to but not including 101.  The
result tends to be fewer off-by-one errors, and code which is
easier to understand.

Finally, a test like x!=100 implies that x==101 means continue; it
requires careful study of the code to see whether x could ever be
101 or greater.  When you write x<101 it is perfectly plain that x
is always intended to to less than 101.
-- 

Steve Clamage, TauMetric Corp, steve at taumet.com



More information about the Comp.lang.c mailing list