C Programming/setjmp.h

setjmp.h is a header defined in the C standard library to provide "non-local jumps": control flow that deviates from the usual subroutine call and return sequence. The complementary functions   and   provide this functionality.

A typical use of /  is implementation of an exception mechanism that utilizes the ability of   to reestablish program or thread state, even across multiple levels of function calls. A less common use of  is to create syntax similar to coroutines.

Member functions
saves the current environment (i.e., the program state) at some point of program execution, into a platform-specific data structure which can be used, at some later point of program execution, by   to restore the program state to that which was saved by   into. This process can be imagined to be a "jump" back to the point of program execution where  saved the environment. The (apparent) return value from  indicates whether control reached that point normally or from a call to. This leads to a common idiom:.

POSIX.1 does not specify whether  and   save or restore the current set of blocked signals &mdash; if a program employs signal handling it should use POSIX's  /.

Member types
The C99 Rationale describes  as being an array type for backwards compatibility; existing code refers to   storage locations by name (without the   address-of operator), which is only possible for array types.

Caveats and limitations
When a "non-local goto" is executed via /, normal "stack unwinding" does not occur and therefore, any required cleanup actions such as closing file descriptors, flushing buffers, freeing heap-allocated memory, etc., do not occur.

If the function in which  was called returns, it is no longer possible to safely use   with the corresponding   object. This is because the stack frame is invalidated when the function returns. Calling  restores the stack pointer, which—because the function returned—would point to a non-existent and potentially overwritten/corrupted stack frame.

Similarly, C99 does not require that  preserve the current stack frame. This means that jumping into a function which was exited via a call to  is undefined. However, most implementations of  leave the stack frame intact, allowing   and   to be used to jump back-and-forth between two or more functions—a feature exploited for multitasking.

Compared to mechanisms in higher-level programming languages such as Python, Java, C++, C#, and even pre-C languages such as Algol 60, the technique of using /  to implement an exception mechanism is uninspiring. These languages provide more powerful exception handling techniques, while languages such as Scheme, Smalltalk, and Haskell provide even more general continuation-handling constructs.

Simple example
This example shows the basic idea of setjmp. Main calls first, which in turn calls second. The "second" function jumps back into main, skipping "first"'s print statement.

When executed, the above program will output: second main Notice that although the  subroutine gets called, " " never is printed. " " gets printed as the conditional statement  is executed a second time.

Exception handling
In this example,  is used to bracket exception handling, like   in some other languages. The call to  is analogous to a   statement, allowing an exception to return an error status directly to the. The following code adheres to the 1999 ISO C standard and Single UNIX Specification by invoking  in a limited range of contexts: Following these rules can make it easier for the implementation to create the environment buffer, which can be a sensitive operation. More general use of  can cause undefined behaviour, such as corruption of local variables; conforming compilers and environments are not required to protect or even warn against such usage. However, slightly more sophisticated idioms such as  are common in literature and practice, and remain relatively portable. A simple conforming methodology is presented below, where an additional variable is maintained along with the state buffer. This variable could be elaborated into a structure incorporating the buffer itself.
 * As the condition to an,   or iteration statement
 * As above in conjunction with a single  or comparison with an integer constant
 * As a statement (with the return value unused)

Cooperative multitasking
C99 provides that  is guaranteed to work only when the destination is a calling function, i.e., that the destination scope is guaranteed to be intact. Jumping to a function that has already terminated by  or   is undefined. However, most implementations of  do not specifically destroy local variables when performing the jump. Since the context survives until its local variables are erased, it could actually be restored by. In many environments (such as Really Simple Threads and TinyTimbers), idioms such as  can allow a called function to effectively pause-and-resume at a.

This is exploited by thread libraries to provide cooperative multitasking facilities without using  or other fiber facilities. Whereas  is a library service which can create an execution context in heap-allocated memory and can support other services such as buffer overflow protection, abuse of   is implemented by the programmer, who may reserve memory on the stack and fail to notify the library or operating system of the new operating context. On the other hand, a library's implementation of  may internally use   in a fashion similar to this example to save and restore a context, after it has been initialised somehow.

Considering that  to a child function will generally work unless sabotaged, and , as part of POSIX, is not required to be provided by C implementations, this mechanism may be portable where the   alternative fails.

Since no exception will be generated upon overflow of one of the multiple stacks in such a mechanism, it is essential to overestimate the space required for each context, including the one containing  and including space for any signal handlers that might interrupt regular execution. Exceeding the allocated space will corrupt the other contexts, usually with the outermost functions first. Unfortunately, systems requiring this kind of programming strategy are often also small ones with limited resources.