C Reference ยท ctype.h, math.h and others
C setjmp() and longjmp() functions
Reference for setjmp.h: save a point in your program with setjmp(), jump back from deep inside nested calls with longjmp(), and avoid the undefined behavior traps.
setjmp() and longjmp() from <setjmp.h> give C a very primitive form of exception handling. setjmp(env) saves the current execution context (stack pointer, program counter and a few registers) in a jmp_buf and returns 0. Later, longjmp(env, value) abandons whatever the program is doing, however deep in nested function calls, and resumes at the setjmp call, which now returns value instead.
Think of it as a goto that can leave a function. It is used for error recovery in parsers and interpreters, for escaping from deeply nested loops, and in some coroutine tricks. It is also easy to misuse: nothing is cleaned up on the way out, and a long list of rules decides whether your program is defined at all.
#include <setjmp.h> jmp_buf env; if (setjmp(env) == 0) { /* first pass: do the risky work, which may call longjmp(env, 1) */ } else { /* we got here from longjmp: recover */ }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
Syntax
#include <setjmp.h> typedef /* array type */ jmp_buf; int setjmp(jmp_buf env); /* a macro */ [[noreturn]] void longjmp(jmp_buf env, int val);
| Name | Description |
|---|---|
env |
A jmp_buf that receives the saved context (setjmp) or identifies where to jump back to (longjmp). |
val |
The value that setjmp appears to return after the jump. If it is 0, 1 is used instead. |
Returns: setjmp returns 0 when it is called directly, and the nonzero val when control arrives through longjmp. longjmp never returns.
Errors / undefined behavior: the behavior is undefined if the function that called setjmp has already returned when you call longjmp, if longjmp is called from a different thread than the matching setjmp, if setjmp appears in a context other than the allowed ones (below), or if you jump out of the scope of a variable length array. A non-volatile local variable modified between setjmp and longjmp has an indeterminate value afterwards.
Usage notes
- Where
setjmpmay appear. Only as the whole controlling expression ofif,switch,whileorfor, compared with an integer constant (setjmp(env) == 0), negated (!setjmp(env)), or as an expression statement (setjmp(env);). Writingint r = setjmp(env);often works but is technically undefined, which is why the examples useswitchandif. setjmpis a macro. You cannot take its address or declare a function pointer to it.- The target frame must still exist. After
returnfrom the function that calledsetjmp, its savedjmp_bufpoints to a dead stack frame. Jump only "upward" the call chain, never into a function that has finished. - Use
volatilefor locals that change. Any automatic variable whose value is modified aftersetjmpand read again after the jump must bevolatile, otherwise the compiler may have kept it in a register thatlongjmprestores to an older value. Variables not modified aftersetjmpare safe. - No cleanup.
longjmpdoes not callfree, close files, unlock mutexes or restore anything. Every frame it skips leaks whatever it owned. Keep ownership simple (a single cleanup point after thesetjmpbranch) or do not use it. - Signals and the signal mask. Whether
setjmpsaves the signal mask is not specified by ISO C. POSIX providessigsetjmpandsiglongjmpfor that; see sigaction. Jumping out of a signal handler is only allowed in narrow cases. - Cost. Both operations are O(1) and cheaper than error-code propagation through many frames, but they disable some compiler optimizations around the
setjmpcall. - Readability. The control flow is invisible at the call sites. Prefer returning error codes in new code and reserve
longjmpfor contained cases such as a parser that bails out in one place. - Standard version: C89. In C23
longjmpis declared[[noreturn]]; older headers use_Noreturn.