C Library Macro - setjmp()
C Standard Library - <setjmp.h>
Description
The C library macro int setjmp(jmpbuf environment): Creates a local jmpbuf buffer and initializes it for a future jump back to this point. This routine saves the calling environment of the program in the buffer pointed to by the env parameter, which will be used by longjmp
. If returning directly from the setjmp call, it returns 0. If returning from a longjmp
call that restores the environment, it returns a non-zero value.
Declaration
Here is the declaration for the setjmp()
macro.
int setjmp(jmp_buf environment)
Parameters
- environment -- This is an object of type jmp_buf used to store environment information.
Return Value
This macro may return more than once. The first time, when called directly, it always returns zero. When called with environment information set by longjmp
, it returns again, this time returning the value passed to longjmp
as the second argument.
Example
The following example demonstrates the use of the setjmp()
macro.
#include <stdio.h>
#include <setjmp.h>
static jmp_buf buf;
void second(void) {
printf("second\n"); // Print
longjmp(buf,1); // Jump back to the setjmp call site - causing setjmp to return 1
}
void first(void) {
second();
printf("first\n"); // This line will not be executed
}
int main() {
if ( ! setjmp(buf) ) {
first(); // setjmp returns 0 before entering this line
} else { // When longjmp jumps back, setjmp returns 1, thus entering this block
printf("main\n"); // Print
}
return 0;
}
Let's compile and run the above program, which will produce the following result:
second
main