----- Original Message -----
Subject: RE: [AD] Small change in
file.c
Peter Wang writes:
> > why
doesn't this code in file.c (line: 342) use a for loop?
> ...
> > Is there a good reason a
while loop is used?
>
>
Personal preference I guess. I'd use a `while' loop there too.
for loops are a very easily abused feature of the C
language,
because you can do almost any type of
looping construct with
them, and can also put other
code which has nothing at all to
do with the loop
inside what looks like the loop control
section. This
can produce some very strange statements with
all
sorts of odd side-effects, and can be very confusing to
read as when people see a for statement they tend to think
"iterate over a fixed number of items or values".
My personal rule of good coding style is to limit for
loops
to a small set of simple, idiomatic types which
any C coder
will instantly recognise, such as:
// iterate over a range of values
for (i=a; i<b; i++) {
...
}
// iterate through a linked list
for (ptr=head; ptr; ptr=ptr->next)
{
...
}
// iterate through an STL container
for (ContainerType::iterator it =
container.begin(); it != container.end(); it++) {
..
}
Any more unusual types of loop (for instance using <=
instead
of a < condition, or decrementing rather
than incrementing
the pointer, or with multiple exit
conditions), are risky
as someone in a hurry will tend
to assume they are one of
the standard versions. In
those cases I prefer to write it
as a while loop,
which don't have the same limited number of
idiomatic
uses, so people are more likely to look carefully
and
notice that something odd is going on. By the same
principle, I think it is bad style to use a while loop for
one of these idiomatic cases. Experienced C coders
will
recognise:
for (i=0; i<n; i++) {
...
}
more quickly than:
i = 0;
while (i < n) {
...
i++;
}
And where possible, it's good to rearrange loops to fit
into
one of the idiomatic styles. The use of <
rather than <= is
almost universal as a terminator
(because C arrays are zero
based), hence if you want
to process everything up to and
including the end
value, you could write:
for (i=0; i<=n; i++) {
...
}
but someone reading that might assume it was a mistake,
and
that you are accidentally processing one element
past the end
of your array. If you instead write this
as:
for (i=0; i<n+1; i++) {
...
}
you make it much more obvious that you really do mean to
include that extra one value, so everyone will know
this
isn't a mistake, and will be in less danger of
'fixing'
it for you :-)
Shawn.