Careful "for" Loops

Jim Giles jlg at cochiti.lanl.gov
Tue Mar 26 04:43:48 AEST 1991


In article <4176 at rwthinf.UUCP>, berg at 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<trip_count; i+=incr, j++) ...

The restrictions are now: high-low <= UNSIGNED_LONG_MAX, incr != 0,
and high >= 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 



More information about the Comp.lang.c mailing list