P
pete
Tim Rentsch wrote:
My preferences for while loop vs. for loop, tends to go
according to aesthetics which I don't consider to be
related to style, in the sense that "good programming style"
means enhanced maintainability.
I think that for loops look funny when they have
empty expressions or statements.
I think your originally posted function definition
was only busy enough to fill up a while loop.
while( s[n] ) n++;
My preference for a loop to do something N times,
is a count down while loop.
void do_something_N_times(unsigned n)
{
while (n-- != 0) {
/* do something */
}
}
Always using a compound statement as a loop body,
*is* something that I consider to be a style issue.
Normally I expect 'for' statements are used when iterating over known
quantities; also they usually "do" something with each element
iterated over. Of course these conditions needn't be true but most
often they are. So the for loop here seems a little off.
On the other hand, 'while' statements are often used to establish
postconditions. The code
which is more or less the definition for 'n' being the length of the
string 's'. (Initializing 'n' on its declaration is just a convenient
shortening of an initializing expression.)
Certainly you're right that operationally the two functions are
equivalent. It just seems to be a little more mental effort to be
sure that the 'for' code is doing the right thing - it's less clear
or less obvious or perhaps both. For these reasons I tend to favor
the 'while' form here.
My preferences for while loop vs. for loop, tends to go
according to aesthetics which I don't consider to be
related to style, in the sense that "good programming style"
means enhanced maintainability.
I think that for loops look funny when they have
empty expressions or statements.
I think your originally posted function definition
was only busy enough to fill up a while loop.
while( s[n] ) n++;
My preference for a loop to do something N times,
is a count down while loop.
void do_something_N_times(unsigned n)
{
while (n-- != 0) {
/* do something */
}
}
Always using a compound statement as a loop body,
*is* something that I consider to be a style issue.