Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!uunet!mstan!amull From: amull@Morgan.COM (Andrew P. Mullhaupt) Newsgroups: comp.lang.c Subject: Re: Array bounds checking with C???? Message-ID: <1622@s6.Morgan.COM> Date: 4 Sep 90 12:57:14 GMT References: <7611@ucdavis.ucdavis.edu> <26196@mimsy.umd.edu> <1589@redsox.bsw.com> Organization: Morgan Stanley & Co. NY, NY Lines: 33 In article <1589@redsox.bsw.com>, campbell@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'; I hope that there are lots of compilers which can tell the difference between these. "Off by one" in the number of increments is one of the classic hazards of side effect assignments. (See my still as yet unposted "for statement considered harmful in C"...) The next problem can happed if p is of type (char *) and array is type (double[]). On machines where sizeof(char) != sizeof(double) (and there are one or two of these ill-behaved monstrosities around...) you don't get the same result. But seriously, folks... the exposure to aliasing of the two fragments is different, and if p is not used carefully subsequent to exiting the loop, optimization may be lost - i.e. a mere mortal compiler might not be able to generate the identical code for the kind of loop where the array is accessed via a pointer alias and the loop calls a function with either p or array as an argument. (Suppose the source for the function in the loop is not in the file where the loop is. How is the compiler supposed to know that a side effect doesn't prevent the use of a register for the aliased quanitity?) Later, Andrew Mullhaupt