Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Posting-Version: version B 2.10.2 9/18/84 SMI; site sun.uucp Path: utzoo!watmath!clyde!burl!ulysses!allegra!mit-eddie!genrad!decvax!decwrl!sun!shannon From: shannon@sun.uucp (Bill Shannon) Newsgroups: net.lang.c Subject: Re: String copy idiom. Message-ID: <2040@sun.uucp> Date: Mon, 11-Mar-85 04:16:59 EST Article-I.D.: sun.2040 Posted: Mon Mar 11 04:16:59 1985 Date-Received: Wed, 13-Mar-85 00:49:59 EST References: <7044@watdaisy.UUCP> <3448@alice.UUCP> <464@petsd.UUCP> Organization: Sun Microsystems, Inc. Lines: 46 > In article <3448@alice.UUCP> ark@alice.UUCP (Andrew Koenig) writes: > >If s and t are char pointers in registers, > > > > while (*s++ = *t++) ; > > > >generates the best code I could possibly imagine. > > > > while ((*s = *t) != '\0') {s++; t++;} > > > >is considerably worse. Try it with register variables on your compiler. > > Ok, I did. The second sequence generates less code than the first sequence > on our machine (Perkin-Elmer). This is due to the fact that our machine > doesn't support auto-increment in hardware. The C compiler has to "fake" it. > > regards, > joe On the Sun the first generates the obvious two instruction loop while the second generates a five instruction loop: register char *s, *t; while (*s++ = *t++) ; L14: movb a4@+,a5@+ jne L14 while ((*s = *t) != '\0') {s++; t++;} L17: movb a4@,a5@ jeq LE12 addql #1,a5 addql #1,a4 jra L17 LE12: Note that the two loops differ in the values of s and t at loop termination. I consider the first loop to be more obvious, it is after all the standard C idiom for copying a string. If you "optimize" your code for one machine by writing the second loop, you may be pessimizing it for other machines. Such is the nature of C and C programmers. Bill Shannon Sun Microsystems, Inc.