SETJMP - prepare for non-local GOTO.

(ANSI Standard)

Usage:

#include <setjmp.h>
value = setjmp( env );

Where:

jmp_buf env;
is a stack environment (see below).
int value;
is a special value (see below).

Description:

"setjmp" saves the current stack environment in "env" for later use. The type "jmp_buf" is defined in <setjmp.h>. "setjmp" returns the value 0.

"setjmp" is used in connection with the "longjmp" function. "longjmp" is invoked with a call of the form

longjmp( env, value );

where "env" is the same one used in "setjmp" and "value" is an integer. "longjmp" artificially sets the program environment back the way it was when the "setjmp" was invoked and makes it look like the "setjmp" has returned once more. This time though when the "setjmp" returns, the value it returns is the "value" specified in the call to "longjmp". For example,

if ( setjmp(env) == -1 ) {
   /* Error return */
}
/* normal processing here */
           ...
longjmp( env, -1 );

When the "setjmp" is executed the first time, it saves the environment in "env" and returns a zero. Thus the normal processing takes place. When the "longjmp" is executed, the environment saved in "env" is restored. "longjmp" makes it appear as if the original "setjmp" has just returned again, this time with a value of -1. Thus the error return processing is invoked.

"longjmp" does some house-cleaning as it jumps back to "setjmp", but it does not undo everything that has occurred. For example, if some space has been allocated through "malloc" between the "setjmp" and the "longjmp", the space is not freed. However, space allocated with "alloc" or "_allocate" will be freed.

If the function that called the "setjmp" is no longer on the stack when the "longjmp" is executed, the program will likely abort.

Notes:

According to the ANSI standard, "setjmp" is only guaranteed to work in the following contexts:

In fact, this version of C accepts "setjmp" in any context, but this is an extension to the ANSI standard.

Copyright © 1996, Thinkage Ltd.