save the calling environment, for use by longjmp()
#include <setjmp.h> int setjmp( jmp_buf env );
The setjmp() macro saves its calling environment in its env argument, for subsequent use by the longjmp() function.
In some cases, error handling can be implemented by using setjmp() to record the point to which a return will be made following an error. When an error is detected in a called function, that function uses longjmp() to jump back to the recorded position. The original function that called setjmp() must still be active (that is, it cannot have returned to the function that called it). In effect, this implements a nonlocal goto.
Special care must be exercised to ensure that any side effects that are left undone (allocated memory, opened files, and so on) are satisfactorily handled.
The setjmp() function returns zero when it is initially called. The return value will be nonzero if the return is the result of a call to the longjmp() function. An if statement is often used to handle these two returns. When the return value is zero, the initial call to setjmp() has been made; when the return value is nonzero, a return from a longjmp() has just occurred.
/* show LONGJMP, SETJMP */ #include <stdio.h> #include <setjmp.h> jmp_buf env; int main( void ) { int ret_val; ret_val = 293; if( 0 == ( ret_val = setjmp( env ) ) ) { printf( "after setjmp %d\n", ret_val ); rtn(); printf( "back from rtn %d\n", ret_val ); } else { printf( "back from longjmp %d\n", ret_val ); } return( EXIT_SUCCESS ); } rtn() { printf( "about to longjmp\n" ); longjmp( env, 14 ); }
produces the output:
after setjmp 0 about to longjmp back from longjmp 14
ANSI
Safety: | |
---|---|
Interrupt handler | No |
Signal handler | Yes |
Thread | Yes |
setjmp() is a macro.