a style question
Richard Harter
rh at smds.UUCP
Mon Oct 1 20:12:01 AEST 1990
In article <1990Sep30.050655.13212 at zoo.toronto.edu>, henry at zoo.toronto.edu (Henry Spencer) writes:
> In article <7341 at darkstar.ucsc.edu> 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++) ...
> Most people find it more readable with a bit of space and the statement
> on the next line:
> for (x = 0; x != 100; x++)
> ...
> The cautious would also recommend `x <= 100', but in this situation that
> is arguable.
> I assume `x' is an integer variable, not floating-point.
The original construction is bad style unless the value of x is being
altered within the loop so that x==100 is the termination condition. If
this is the typical loop structure <perform loop body for x = 0 ... 99>
the normal idiom is
for (x=0;x<100;x++) {...}
There is a good reason for using this idiom if you think about it. In
C an array of size N has valid indices from 0 through N-1. Since many
loops reference arrays it is normal for an N times loop to use the same
indexing pattern so that the termination condition for a loop with
increasing indices is index >=N or index<N.
There is a general rule of code writing that the termination conditions
used in loops should match the actual termination condition. If the
actual condition is x<100 that is what you should use rather than the
weaker condition x!=100. Note that the proposed text fails if the body
of the loop ever alters the value of x to be greater than 100.
As a further point. If Henry Spencer, who is an expert, can mistranslate
this construction, you can take it as pragmatic evidence that it is
dubious.
--
Richard Harter, Software Maintenance and Development Systems, Inc.
Net address: jjmhome!smds!rh Phone: 508-369-7398
US Mail: SMDS Inc., PO Box 555, Concord MA 01742
This sentence no verb. This sentence short. This signature done.
More information about the Comp.lang.c
mailing list