Path: utzoo!mnetor!uunet!husc6!cmcl2!brl-adm!adm!MAILER%ALASKA.BITNET@CUNYVM.CUNY.EDU From: MAILER%ALASKA.BITNET@CUNYVM.CUNY.EDU Newsgroups: comp.lang.c Subject: Undelivered mail Message-ID: <12325@brl-adm.ARPA> Date: 12 Mar 88 21:06:52 GMT Sender: news@brl-adm.ARPA Lines: 68 Subject: Re: How not to write a loop [Non-Deliverable: User does not exist or has never logged on] Reply-To: Info-C@BRL.ARPA Received: From UWAVM(MAILER) by ALASKA with Jnet id 8423 for SXJVK@ALASKA; Sat, 12 Mar 88 11:39 AST Received: by UWAVM (Mailer X1.25) id 5718; Sat, 12 Mar 88 12:38:31 PST Date: Fri, 11 Mar 88 06:21:22 GMT Reply-To: Info-C@BRL.ARPA Sender: Info-C List From: "James E. Prior" Subject: Re: How not to write a loop Comments: To: info-c@BRL-SMOKE.arpa To: Vic Kapella 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