[net.lang.c] longjmp

dpg@busch.UUCP (David Grossman) (08/24/84)

[]
I have an application for a subroutine to call itself recursively, then
erase the recursive level, so that it returns directly to main. This was
implemented using longjmp(). The environment is set in the first call.
Then the next call executes longjmp to pop back to the stack environment
that was in effect during the first call.

This is a great use for longjmp, but I've never seen it done before. Of
course, the code could be written to return through main, then call sub,
but I think the code  is much cleaner this way, especially if there are
several points in main that can call sub. Here's the code:

	int mult;		/* flag to tell if sub is recursing */

	main()
	{
		...
		mult = 0;
		sub();
		...
	}

	sub()
	{
		...
		if (mult == 0)
			setjmp(env);	/* set return pointer on first call */
		else {
			mult = 0;
			longjmp(env,0);	/* erase the recursion level */
		}
		...
		mult = 1
		sub();			/* call sub recursively */
	}

David Grossman			..!ihnp4!we53!busch!dpg
Anheuser-Busch Companies	314/577-3125
One Busch Place, Bldg. 202-4
St. Louis, MO  63118

gwyn@BRL-VLD.ARPA (08/26/84)

From:      Doug Gwyn (VLD/VMB) <gwyn@BRL-VLD.ARPA>

I don't see how using setjmp/longjmp to short-circuit recursion is
any "cleaner" than the following:

main()
{	...
	sub();
	...
}

sub()
{	static int level = 0;
	...
	if ( ++level <= 1 )
		sub();
	--level;
}

This method also lets you select a more general "recursion depth",
useful for example in searching game trees, and sub() can return
a value to its parent if required (as it usually would be in a
practical application).