Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!swrinde!zaphod.mps.ohio-state.edu!wuarchive!udel!rochester!kodak!ispd-newsserver!ism.isc.com!bud.sos.ivy.isc.com!willcr From: willcr@bud.sos.ivy.isc.com (Will Crowder) Newsgroups: comp.lang.c Subject: Re: Careful "for" Loops Message-ID: <1991Mar21.181807.24059@ism.isc.com> Date: 21 Mar 91 18:18:07 GMT References: <15524@smoke.brl.mil> Sender: usenet@ism.isc.com (Ism Usenet News) Reply-To: willcr@ivy.isc.com Followup-To: comp.lang.c Organization: Interactive Systems Corp. Lines: 37 In article <15524@smoke.brl.mil>, gwyn@smoke.brl.mil (Doug Gwyn) writes: |> In article mcdaniel@adi.com (Tim McDaniel) writes: |> >1) How do you code a "for" loop to avoid overflow gotchas? |> |> (a) Use pointers instead. |> (b) Don't push against the very limit of the representable range. |> (c) Use unsigned types and compare for equality with zero. |> (d) Consider each case on its own merits. On a somewhat related note, the ANSI C standard guarantees that the address of the element one past the end of an array is representable and won't overflow. This makes loops like { int a[10]; int *p, *q; /* point q and at end a */ q = &a[sizeof a / sizeof a[0]]; for (p = a; p != q; p++) useful_work_goes_here(); } work properly. [The (sizeof a / sizeof a[0]) expression keeps the explicit knowledge of the size of the array in its declaration.] The implementation must place the array a such that &a[10] is representable and will not overflow. Will -------------------------------------------------------------------------------- Will Crowder, MTS | "I belong to no organized politcal party. (willcr@ivy.isc.com) | I'm a democrat." INTERACTIVE Systems Corp. | -- Will Rogers