Next: Non-Local Exits and Signals, Previous: Non-Local Intro, Up: Non-Local Exits
Here are the details on the functions and data structures used for performing non-local exits. These facilities are declared in setjmp.h.
Objects of type
jmp_buf
hold the state information to be restored by a non-local exit. The contents of ajmp_buf
identify a specific place to return to.
When called normally,
setjmp
stores information about the execution state of the program in state and returns zero. Iflongjmp
is later used to perform a non-local exit to this state,setjmp
returns a nonzero value.
This function restores current execution to the state saved in state, and continues execution from the call to
setjmp
that established that return point. Returning fromsetjmp
by means oflongjmp
returns the value argument that was passed tolongjmp
, rather than0
. (But if value is given as0
,setjmp
returns1
).
There are a lot of obscure but important restrictions on the use of
setjmp
and longjmp
. Most of these restrictions are
present because non-local exits require a fair amount of magic on the
part of the C compiler and can interact with other parts of the language
in strange ways.
The setjmp
function is actually a macro without an actual
function definition, so you shouldn't try to `#undef' it or take
its address. In addition, calls to setjmp
are safe in only the
following contexts:
Return points are valid only during the dynamic extent of the function
that called setjmp
to establish them. If you longjmp
to
a return point that was established in a function that has already
returned, unpredictable and disastrous things are likely to happen.
You should use a nonzero value argument to longjmp
. While
longjmp
refuses to pass back a zero argument as the return value
from setjmp
, this is intended as a safety net against accidental
misuse and is not really good programming style.
When you perform a non-local exit, accessible objects generally retain
whatever values they had at the time longjmp
was called. The
exception is that the values of automatic variables local to the
function containing the setjmp
call that have been changed since
the call to setjmp
are indeterminate, unless you have declared
them volatile
.