Careful "for" Loops
Stan Brown
browns at iccgcc.decnet.ab.com
Tue Mar 26 03:16:47 AEST 1991
In article <1991Mar21.181807.24059 at ism.isc.com>, willcr at bud.sos.ivy.isc.com (Will Crowder) writes:
> 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.
I use
for (p=a; p<a; p++)
Then if my loop also increments p, the loop still terminates.
(Yes, I know my loop _shouldn't_ increment p, but sometimes I
make coding errors.)
My opinions are mine: I don't speak for any other person or company.
email (until 91/4/30): browns at iccgcc.decnet.ab.com
Stan Brown, Oak Road Systems, Cleveland, Ohio, USA +1 216 371 0043
More information about the Comp.lang.c
mailing list