Tail recursion in C

T. William Wells bill at twwells.com
Sun Jul 16 10:26:20 AEST 1989


In article <30050 at ucbvax.BERKELEY.EDU> jwl at ernie.Berkeley.EDU.UUCP (James Wilbur Lewis) writes:
: 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. :-)

Well, here's an example: I had a directed graph I wanted to traverse
and wanted to process paths of a specified through it, from the leaves
toward the "root". The code looked something like:

/* traverse(root, length, (NODELIST *)0); length > 0 */

void
traverse(node, length, next)
NODE    *node;
int     length;
NODELIST *next;
{
	NODELIST *np;
	NODELIST link;

	link.next = next;
	link.node = node;
	if (length == 1) {
		process_path(&link);
	} else {
		for (np = node->list; np; np = np->next) {
			traverse(np->node, length - 1, &link);
		}
	}
}

The idea is that on the stack is a linked list of NODELISTs which can
be scanned for each NODE on the path by the process_path() routine.

Note that there are no dangling pointers.

---
Bill                    { uunet | novavax | ankh | sunvice } !twwells!bill
bill at twwells.com



More information about the Comp.lang.c mailing list