Careful "for" Loops

Will Crowder willcr at bud.sos.ivy.isc.com
Fri Mar 22 04:18:07 AEST 1991


In article <15524 at smoke.brl.mil>, gwyn at smoke.brl.mil (Doug Gwyn) writes:
|> In article <MCDANIEL.91Mar19124111 at dolphin.adi.com> mcdaniel at 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 at ivy.isc.com)         |  I'm a democrat."  
INTERACTIVE Systems Corp.    |		-- Will Rogers



More information about the Comp.lang.c mailing list