Array bounds checking with C????

Walter Bright bright at Data-IO.COM
Sat Sep 8 04:40:53 AEST 1990


In article <1990Sep6.203031.29254 at laguna.ccsf.caltech.edu> jimmy at tybalt.caltech.edu (Jimmy Hu) writes:
<In article <1589 at redsox.bsw.com> campbell at redsox.bsw.com (Larry Campbell) writes:
<<Are there actually any current compilers out there that are so stupid that
<<they generate substantially different code for the following two code fragments?
<<
<<    /* Fragment 1 */
<<    for (p = array; p < &array[ARRAY_SIZE]; p++)
<<	*p = '\0';
<<
<<    /* Fragment 2 */
<<    for (i = 0; i < ARRAY_SIZE; i++)
<<	array[i] = '\0';
<<
<The final result will still be the
<same, in that the array is cleared to 0, but I don't think that the compiler
<will "convert" or "optimize" the second to the first or vice versa.

Zortech's optimizer will do this conversion.

<After all,
<assuming it is trying to convert the second to the first, where is it going to
<get a pointer from? Create one?

Yes.

<How will i become ARRAYSIZE after exiting the
<loop? There has to be SOME code difference. I don't think that a compiler
<should have to be sophisticated enough to "guess" at the intent of your code.

If i is used after the exit of the loop, the expression
	i = p - array;
is added to each branch that exits the loop.

<(Another article stated that a MIPS compiler actually generated the SAME
<code for the two fragments. I find that hard to believe unless index i was
<never used anywhere else. Even so, that must have been a sophisticated
<compiler.) 

Thanks for the compliment!

These kinds of optimizations are fairly well understood. Check out
Aho and Ullman's "Compilers" book (the dragon book).



More information about the Comp.lang.c mailing list