setjmp() General Function setjmp()
Perform non-local goto
#include <setjmp.h>
int setjmp(env) jmp_buf env;
The function call is the only mechanism that C provides to trans-
fer control between functions. This mechanism, however, is in-
adequate for some purposes, such as handling unexpected errors or
interrupts at lower levels of a program. To answer this need,
setjmp helps to provide a non-local goto facility. setjmp saves
a stack context in env, and returns value zero. The stack con-
text can be restored with the function longjmp. The type decla-
ration for jmp_buf is in the header file setjmp.h. The context
saved includes the program counter, stack pointer, and stack
frame.
***** Example *****
The following gives a simple example of setjmp and longjmp.
#include <setjmp.h>
jmp_buf env; /* place for setjmp to store its environment */
main()
{
int rc;
if(rc = setjmp(env)) { /* we come here on return */
printf("First char was %c\n", rc);
exit(0);
}
subfun(); /* this never returns */
}
subfun()
{
char buf[80];
COHERENT Lexicon Page 1
setjmp() General Function setjmp()
do {
printf("Enter some data\n");
gets(buf); /* get data */
} while(!buf[0]); /* retry on null line */
longjmp(env, buf[0]); /* buf[0] must be non zero */
}
***** See Also *****
general functions, getenv(), longjmp()
***** Notes *****
Programmers should note that many user-level routines cannot be
interrupted and reentered safely. For that reason, improper use
of setjmp and longjmp can create mysterious and irreproducible
bugs. The use of longjmp to exit interrupt exception or signal
handlers is particularly hazardous.
COHERENT Lexicon Page 2