Skip to content
Tutorials Center
My learning

Topics

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.

C
#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

C Recovering from an error deep in a call

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.

C Different return values with switch

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

C
#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 setjmp may appear. Only as the whole controlling expression of if, switch, while or for, compared with an integer constant (setjmp(env) == 0), negated (!setjmp(env)), or as an expression statement (setjmp(env);). Writing int r = setjmp(env); often works but is technically undefined, which is why the examples use switch and if.
  • setjmp is a macro. You cannot take its address or declare a function pointer to it.
  • The target frame must still exist. After return from the function that called setjmp, its saved jmp_buf points to a dead stack frame. Jump only "upward" the call chain, never into a function that has finished.
  • Use volatile for locals that change. Any automatic variable whose value is modified after setjmp and read again after the jump must be volatile, otherwise the compiler may have kept it in a register that longjmp restores to an older value. Variables not modified after setjmp are safe.
  • No cleanup. longjmp does not call free, close files, unlock mutexes or restore anything. Every frame it skips leaks whatever it owned. Keep ownership simple (a single cleanup point after the setjmp branch) or do not use it.
  • Signals and the signal mask. Whether setjmp saves the signal mask is not specified by ISO C. POSIX provides sigsetjmp and siglongjmp for 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 setjmp call.
  • Readability. The control flow is invisible at the call sites. Prefer returning error codes in new code and reserve longjmp for contained cases such as a parser that bails out in one place.
  • Standard version: C89. In C23 longjmp is declared [[noreturn]]; older headers use _Noreturn.