<setjmp.h> - Non-local
jumps
jump to: demonstration of <setjmp.h>
If function main calls function A, and in turn function
A calls function B, then control normally passes back to
A upon exiting from B, and then main upon exiting from A.
However, it is possible to return from function B directly
to main without returning via function A. Such a change
in behavior is possible by using the following functions.
void longjmp(jmp_buf env, int retrval);
int setjmp(jmp_buf env);
The longjmp function restores the processor environment
previously saved in env by setjmp. These functions provide
a mechanism for executing inter-function gotos, and are
usually used to pass control to error recovery code.
A call to setjmp causes the current processor environment
to be saved in env. Allowing call to longjmp restores the
saved environment and causes execution to resume at a point
immediately after the corresponding setjmp call. Execution
continues with retrval as the return value from setjmp.
As long as longjmp is called before the function calling
setjmp returns, all variables local to the routine will
have the same value as when setjmp was called. However,
register variables may not be restored. Use the volatile
keyword to ensure that local variables ae properly restored.
Esentially setjmp marks a place in a function so
that longjmp can be used to return to that place later.
Example:
#include <stdio.h>
#include <setjmp.h>
typedef enum {false, true} boolean;
jmp_buf mark;
void B(void);
void A(void)
{
printf("function A\n");
B();
printf("returned to function
A");
}
void B(void)
{
static boolean jump = false;
if (jump)
longjmp(mark,
1);
else
printf("function
B\n");
jump = true;
}
int main(void)
{
int counter = 0;
for (; counter <=1; counter++)
{
printf("function
main\n");
if (setjmp(mark))
printf(jumped
back to main from B\n");
else
A();
}
}
Results:
function main
function A
function B
returned to function A
function main
function A
jumped back to main from B
go to <signal.h> back
to top back
to main