Path: utzoo!utgpu!news-server.csri.toronto.edu!mailrus!uunet!cs.utexas.edu!tut.cis.ohio-state.edu!pt.cs.cmu.edu!o.gp.cs.cmu.edu!andrew.cmu.edu!jh4o+ From: jh4o+@andrew.cmu.edu (Jeffrey T. Hutzelman) Newsgroups: comp.lang.c Subject: Re: a style question Message-ID: Date: 1 Oct 90 01:38:52 GMT References: <7341@darkstar.ucsc.edu>, <467@taumet.com> Organization: Carnegie Mellon, Pittsburgh, PA Lines: 63 In-Reply-To: <467@taumet.com> steve@taumet.com (Stephen Clamage) writes: > aryeh@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@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+@andrew.cmu.edu, jhutz@drycas.club.cc.cmu.edu >> Apple // Forever!!! <<