6.12.3 setjmp Function
A macro that saves the current state of the program for later use by the
longjmp
function.
Include
<setjmp.h>
Prototype
int setjmp(jmp_buf env)
Argument
env
- the array where the environment will be stored
Return Value
If the return is from a direct call, setjmp
returns zero. If the return
is from a call to longjmp
, setjmp
returns a non-zero
value, even if longjmp
was called with its val
argument set to 0, in which case setjmp
will return 1.
Remarks
The setjmp
function can return as a result of a direct call, when the
environment is stored, or from a subsequent call to longjmp
, which uses
the stored environment to continue execution from the saved instance of the previously
called setjmp
function.
Example
See the notes at the beginning of this chapter or section for
information on using printf()
or scanf()
(and other functions reading and writing the stdin
or
stdout
streams) in the example code.
#include <stdio.h>
#include <setjmp.h>
#include <stdlib.h>
jmp_buf jb;
void inner (void)
{
longjmp(jb, 5);
}
int main (void)
{
int i;
if((i = setjmp(jb))) {
printf("setjmp returned %d\n", i);
exit(0);
}
printf("setjmp returned 0 - good\n");
printf("calling inner...\n");
inner();
printf("inner returned - bad!\n");
}
Example Output
setjmp returned 0 - good
calling inner...
setjmp returned 5