longjmp() erases recursion level

David Grossman dpg at busch.UUCP
Fri Aug 24 07:03:18 AEST 1984


[]
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



More information about the Comp.lang.c mailing list