Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!zaphod.mps.ohio-state.edu!wuarchive!uunet!mcsun!unido!rwthinf!marvin.e17.physik.tu-muenchen.de!berg From: berg@marvin.e17.physik.tu-muenchen.de (Stephen R. van den Berg) Newsgroups: comp.lang.c Subject: Re: Careful "for" Loops Message-ID: <4176@rwthinf.UUCP> Date: 25 Mar 91 16:24:09 GMT References: Sender: news@rwthinf.UUCP Lines: 26 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@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."