Path: utzoo!utgpu!water!watmath!clyde!att!osu-cis!tut.cis.ohio-state.edu!bloom-beacon!mit-eddie!uw-beaver!tektronix!tekcrl!tekchips!stevev From: stevev@tekchips.TEK.COM (Steve Vegdahl) Newsgroups: comp.misc Subject: Re: Basics of Program Design Summary: but that program is not tail-recursive Message-ID: <3347@tekchips.TEK.COM> Date: 24 Jun 88 22:31:15 GMT References: <901@td2cad.intel.com> <3061@rpp386.UUCP>Distribution: na Organization: Tektronix Inc., Beaverton, Or. Lines: 44 In article , webber@aramis.rutgers.edu (Bob Webber) writes: > In article <3061@rpp386.UUCP>, jfh@rpp386.UUCP (John F. Haugh II) writes: > > ... > > yes, colleges and universities don't seem to big on useful information. > > a friend in college was charged with writing a string length function > > in C for a compiler writing class so he chose the `elegant' solution. > > > > strlen (s) > > char *s; > > { > > if (*s) > > return (strlen (s + 1) + 1); > > else > > return (0); > > } > > > > not such a smart move. always consider the cost of your algorithm. > > A perfectly fine algorithm. Any decent compiler would remove the tail > recursion. Unfortunately, the above program is not tail-recursive. The result of the recursive "strlen" call is incremented before its value is returned. It would take a pretty sophisticated compiler to transform this into an iteration. Among other things, it would probably have to use the associativity of "+". Consider changing the algorithm so that we the elements of a "string" of floating point numbers. (Floating-point addition is not associative.) floatStringSum (s) float *s; { if (*s = 0.0) return (floatStringSum (s + 1) + *s); else return (0.0); } BTW, does a typical C compiler perform tail-call optimization. Steve Vegdahl Computer Research Lab Tektronix Labs Beaverton, Oregon