How not to write a loop

James E. Prior jep at oink.UUCP
Fri Mar 11 16:21:22 AEST 1988


In article <402 at osupyr.UUCP> gae at osupyr.mast.ohio-state.edu.UUCP (Gerald Edgar) writes:
>Lengthy discussion about loops such as:
>
>>>> 	float x;
>>>> 	for (x = 0; x < 20; x += .5) printf("%f\n", x);
                          ^
                          A decimal point would have been nice!
>
>How about this:
>
> 	float x;
> 	for (x = 0; x < 19.75; x += .5) printf("%f\n", x);

Yes, this will work reliably across many machines.  However, your
suggested solution causes another problem, obfuscation of the intended
end value of the loop.

I realize that 19.75 is half the increment less that twenty, but
someone else might not have that much insight.  You should right
your code so that it is obvious how the magic number 19.75 is
derived.

Next step in obviousness:

	for (x=0; x<20.-.5/2.; x+=.5) ...

but even now, it is not clear that the .5 in 20.-.5/2. is the same
.5 as in x+=.5.  The next step in obviousness is:

#define STEP (.5)
	for (x=0; x<20.-STEP/2.; x+=STEP) ...

This is quite handy for someone who never saw the <20 to begin with.
With the way you wrote your solution, someone needing to change the
step to .25 could inadvertently re-introduce reliability problems as
follows:

	for (x=0; x<19.75; x+=.25)

Another step to de-mystify 20. would be nice.

I stronly recommend that you read Elements of Programming Style by
P. J. Plaugher.  You have reinforced one of the reasons I quit OSU.

>  Gerald A. Edgar                               TS1871 at OHSTVMA.bitnet
>  Department of Mathematics                     gae at osupyr.UUCP
>  The Ohio State University  ...{akgua,gatech,ihnp4,ulysses}!cbosgd!osupyr!gae
>  Columbus, OH 43210                            70715,1324  CompuServe
-- 
Jim Prior    {ihnp4|osu-cis}!n8emr!oink!jep    jep at oink.UUCP



More information about the Comp.lang.c mailing list