a style question
Jeffrey T. Hutzelman
jh4o+ at andrew.cmu.edu
Mon Oct 1 11:38:52 AEST 1990
steve at taumet.com (Stephen Clamage) writes:
> 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
In this case, the "casual reader" would be correct. There ARE 100
iterations: x==0 to x==99.
> for(x=0; x < 101; x++) ...
NO! That would add the iteration for x==100, which is clearly NOT what
is wanted if he wrote x!=100. You mean
for(x=0; x < 100; x++) ...
which would cause the same number of iterations as the original loop.
> 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.
Agreed, but again, you mean T ray[100]; which has 100 elements from
0 to 99.
>
> 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.
This is correct. Good point.
> When you write x<101 it is perfectly plain that x is always
> intended to to less than 101.
Change to "x<100" and "less than 100", which is what was originally
meant.
> --
>
> Steve Clamage, TauMetric Corp, steve at taumet.com
I hope this didn't sound too much like a flame, but I wanted to make
sure the record was kept straight.
-----------------
Jeffrey Hutzelman
America Online: JeffreyH11
Internet/BITNET:jh4o+ at andrew.cmu.edu, jhutz at drycas.club.cc.cmu.edu
>> Apple // Forever!!! <<
More information about the Comp.lang.c
mailing list