Site Tools


h-setjmp

<setjmp.h>

<setjmp.h> provides setjmp and longjmp for non-local jumps: save the current execution context and jump back to it from a deeply nested function, bypassing normal return chains. It's the C equivalent of exceptions but without cleanup machinery.

Use it sparingly—error codes or exceptions are usually clearer. Declare variables volatile to avoid register-caching pitfalls.

Example

This example demonstrates error recovery using setjmp/longjmp to jump from a deep call stack.

// compile: gcc -o setjmpexample setjmpexample.c
// run: ./setjmpexample
// description: non-local jump for error handling
 
#include <setjmp.h>
#include <stdio.h>
 
static jmp_buf err_env;
 
void level3() {
    printf("level3: error detected\n");
    longjmp(err_env, 1);
}
 
void level2() { level3(); }
void level1() { level2(); }
 
int main() {
    if (setjmp(err_env) == 0) {
        printf("calling level1...\n");
        level1();
        printf("never reached\n");
    } else {
        printf("caught error at top level\n");
    }
    return 0;
}

Common functions and types

  • jmp_buf: buffer to hold execution context
  • setjmp(buf): save context and return 0 (or non-zero if jumped to)
  • longjmp(buf, val): restore context and return val from setjmp (val cannot be 0)
  • volatile: declare variables to prevent register caching pitfalls across longjmp
h-setjmp.md · Last modified: by 127.0.0.1