Careful "for" Loops

Stephen R. van den Berg berg at marvin.e17.physik.tu-muenchen.de
Tue Mar 26 02:24:09 AEST 1991


Tim McDaniel writes:
>Case a)
>   semi-open intervals, like [low,high).
>Case b)
>   closed intervals, like [low,high].

Use case a) like intervals, seems to be more intuitive (more "round" numbers).

>1) How do you code a "for" loop to avoid overflow gotchas?

 unsigned long i,low,high,incr;
	for(i=low;(long)(high-i)>0;i+=incr)

The only restrictions here are: high-low<=LONG_MAX && incr<=LONG_MAX && incr>0

The first restriction can be avoided if you code it as follows:

 unsigned long i,low,high,incr; 
        for(i=low;i-high>=incr;i+=incr)

Restriction is now: high-low<=UNSIGNED_LONG_MAX-incr
--
Sincerely,                 berg at marvin.e17.physik.tu-muenchen.de
           Stephen R. van den Berg.
"I code it in 5 min, optimize it in 90 min, because it's so well optimized:
it runs in only 5 min.  Actually, most of the time I optimize programs."



More information about the Comp.lang.c mailing list