Path: utzoo!mnetor!uunet!husc6!bbn!uwmcsd1!tut.cis.ohio-state.edu!osu-cis!n8emr!oink!jep From: jep@oink.UUCP (James E. Prior) Newsgroups: comp.lang.c Subject: Re: How not to write a loop Message-ID: <245@oink.UUCP> Date: 11 Mar 88 06:21:22 GMT References: <560@naucse.UUCP> <1988Feb11.200149.25172@sq.uucp> <2115@bsu-cs.UUCP> <832@unmvax.unm.edu> <712@cresswell.quintus.UUCP> <928@aucs.UUCP> <402@osupyr.UUCP> Reply-To: jep@oink.UUCP (James E. Prior) Distribution: na Organization: Random Prime Research Institute Columbus, Ohio Lines: 50 Keywords: For Loops Silliness Why In article <402@osupyr.UUCP> gae@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@OHSTVMA.bitnet > Department of Mathematics gae@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@oink.UUCP