Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!zaphod.mps.ohio-state.edu!swrinde!cs.utexas.edu!yale!cmcl2!lanl!cochiti.lanl.gov!jlg From: jlg@cochiti.lanl.gov (Jim Giles) Newsgroups: comp.lang.c Subject: Re: Careful "for" Loops Message-ID: <19064@lanl.gov> Date: 25 Mar 91 18:43:48 GMT References: <4176@rwthinf.UUCP> Sender: news@lanl.gov Reply-To: jlg@cochiti.lanl.gov (Jim Giles) Organization: Los Alamos National Laboratory Lines: 42 In article <4176@rwthinf.UUCP>, berg@marvin.e17.physik.tu-muenchen.de (Stephen R. van den Berg) writes: |> Tim McDaniel writes: |> >Case a) |> > semi-open intervals, like [low,high). |> >Case b) |> > closed intervals, like [low,high]. |> [...] |> unsigned long i,low,high,incr; |> for(i=low;i-high>=incr;i+=incr) |> |> Restriction is now: high-low<=UNSIGNED_LONG_MAX-incr Since this is a Case a) loop, the restriction can be further narrowed (by just the value of incr): unsigned long i, j, low, high, incr, trip_count; ... trip_count = (high-low)/incr; for (i=low, j=0; j= low. (These last two conditions are obvious, but should be bourne in mind anyway.) Similarly, Case b) can be handled with the same restrictions: unsigned long i, j, low, high, incr, trip_count; ... trip_count = (high-low)/incr; i=low; j=0; while (1){ /* loop forever (sort of) */ ... if (j==trip_count) exit; /* exit condition in middle */ i+=incr; j++; } Note that in Case a) the trip_count variable is actually the number of times the loop body is executed. In case b), trip_count is one less than the number of passes through the loop. J. Giles