Tail recursion in C

James Wilbur Lewis jwl at ernie.Berkeley.EDU
Fri Jul 14 18:00:47 AEST 1989


In article <33133 at apple.Apple.COM> landon at Apple.COM (Landon Dyer) writes:
-Whenever someone asks "why can't I tail-recurse in C?" my eyes bug out, my
-vision gets fuzzy, and I basically lose it.  I love tail recursion when I'm
-using Scheme, but I'm completely revolted by the concept in C.
-
-
-Here's what ANSI sez about the semantics of auto scoped variables (section
-2.1.2.3 for you language lawyers -- uppercase "italics" are my own):
-
-[...]
-
-What this means is that you can't tail-recurse if the address of a local can
-"leak out" of its scope.

Eh?  You can tail-recurse just fine, but maybe not do the optimization you'd
want...is that what you meant?  Or did I completely miss your point?

-[...for example, if you take the address of an auto variable and store it
-in a global variable...]

-	Link* gLinkList = 0;
-	
-	void f(int n) {
-	    Link elem;
-	    [...]
-	    gLinkList = &elem;
-	    [...]
-	}

Maybe I'm just being dense, but why would anyone ever want to do this?
When the block containing the auto variable is exited, the variable
ceases to exist and you're left with a (dangling) pointer into the
stack somewhere...right?   Perhaps it's legal C, but under what 
circumstances could a program pulling such a stunt be correct? I mean,
to me it seems almost as dumb as, say, adding pointers. :-)

-I would hate to maintain code like that -- 

Jeez, you're not kidding!  But this appears to be a spectacularly bad
programming practice -- does it make sense to criticize C because it
also happens to be legal?  After all, as they say, there has never been
a language in which it was the least bit difficult to write bad programs... 

-- Jim Lewis
   U.C. Berkeley



More information about the Comp.lang.c mailing list