Supports transfer of control between functions.
The following macros are implementation-defined.
The setjmp function saves the execution environment of the current function. The location in the program that called the setjmp function can subsequently be returned to by calling the longjmp function.
An example of how transfer of control between functions is supported using the setjmp and longjmp functions is shown below.
1 #include <stdio.h>
2 #include <setjmp.h>
3 jmp_buf env;
4 void sub( );
5 void main( )
6 {
7
8 if (setjmp(env)!=0){
9 printf("return from longjmp\n");
10 exit(0);
11 }
12 sub( );
13 }
14
15 void sub( )
16 {
17 printf("subroutine is running \n");
18 longjmp(env, 1);
19 }
The setjmp function is called in line 8. At this time, the environment in which the setjmp function was called is saved in jmp_buf type variable env. The return value in this case is 0, and therefore function sub is called next.
The environment saved in variable env is restored by the longjmp function called within function sub. As a result, the program behaves just as if a return had been made from the setjmp function in line 8. However, the return value at this time is 1 specified by the second argument of the longjmp function. As a result, execution proceeds to line 9.