C setjmp.h Header

Beginner
7 min read
Updated: Oct 2026
3 examples
Live preview

What Is setjmp.h?

<setjmp.h> provides setjmp and longjmp for non-local jumps: save a return point in a jmp_buf, then jump back to it from a nested function—skipping normal returns. Powerful, but easy to misuse.

Remember
#include <setjmp.h>

jmp_buf env;

setjmp(env)          → 0 the first time (bookmark)
longjmp(env, val)    → jumps back; setjmp returns val
                       (if val == 0, setjmp returns 1)

prefer return codes for normal errors
never longjmp to a returned function
UsePrefer
Learn / rare deep recoverysetjmp / longjmp
Everyday errorsreturn codes / errno
Debug-only invariantsassert

How to Use setjmp / longjmp

Plant a bookmark with setjmp, run work, and jump back with longjmp only while that bookmark is still valid.

  1. Add #include <setjmp.h> and declare a jmp_buf (often file-scope or passed by pointer).
  2. Call setjmp(env): first return is 0—run the protected code.
  3. On failure deep in the call chain, call longjmp(env, code) with a non-zero code.
  4. Handle the non-zero return from setjmp in an else (or switch) branch.
PieceRequired?Role
jmp_buf envYesStores the saved execution context
setjmp(env)YesSaves context; returns 0, then later the jump code
longjmp(env, val)On error pathRestores context; does not return to the caller

Pseudocode

Pseudocode
env = empty jmp_buf

result = setjmp(env)
if result == 0:
    // first visit — bookmark planted
    do_work()          // may call longjmp(env, code)
    continue normally
else:
    // jumped here from longjmp
    handle_error(result)

// after longjmp: locals may be stale unless volatile
// never longjmp if the setjmp function already returned

Cheat Sheet

Keep these facts handy while studying non-local jumps.

TopicDetail
Header#include <setjmp.h>
Typejmp_buf — opaque buffer for saved state
First setjmpReturns 0
After longjmp(env, n)setjmp returns n (or 1 if n == 0)
Patternif (setjmp(env) == 0) { work(); } else { handle(); }
Safe localsMark as volatile if used after a jump
Everyday errorsPrefer return -1 / errno instead

Live Preview

Simulate setjmp / longjmp flow: a normal divide, a zero-divide jump, or a custom error code.

Browser simulation of setjmp/longjmp (same idea as the C examples below).

Result
setjmp(env) → 0  (bookmark planted)
divide(10, 2) → Result: 5
(no longjmp)

Program continues normally

Worked Walkthrough — Divide Then Recover

Trace one successful divide and one jump when the divisor is zero.

Calculation
main:
  setjmp(env) → 0          // first visit
  divide(10, 2) → print 5  // OK
  divide(10, 0):
      b == 0 → longjmp(env, 1)

  // control reappears at setjmp
  setjmp(env) → 1          // from longjmp
  else branch → "Division by zero!"
  main continues after the if/else ✓

Skipped: any code after divide(10, 0)
         inside the setjmp == 0 branch

C Examples

Compile with gcc file.c -std=c11 -o out. These teach control flow—prefer return codes in everyday apps.

Example 1 — Recover from Division by Zero

Plant a bookmark in main, then longjmp from a nested function when the divisor is zero.

C
#include <setjmp.h>
#include <stdio.h>

static jmp_buf env;

void divide(int a, int b) {
    if (b == 0) {
        longjmp(env, 1);
    }
    printf("Result: %d\n", a / b);
}

int main(void) {
    if (setjmp(env) == 0) {
        divide(10, 2);
        divide(10, 0);   /* triggers longjmp */
        printf("This line is skipped\n");
    } else {
        printf("Error: Division by zero!\n");
    }

    printf("Program continues after recovery\n");
    return 0;
}

How It Works

  1. First visit. setjmp(env) returns 0, so the if branch runs.
  2. Success path. divide(10, 2) prints Result: 5.
  3. Jump. divide(10, 0) calls longjmp(env, 1)—control returns to setjmp with value 1.
  4. Handler. The else branch prints the error; the “skipped” line never runs, then main continues.

Example 2 — Pass Error Codes Through longjmp

Use distinct non-zero val values so the handler knows why you jumped.

C
#include <setjmp.h>
#include <stdio.h>

static jmp_buf env;

void fail(int code) {
    longjmp(env, code);
}

int main(void) {
    int err = setjmp(env);

    if (err == 0) {
        printf("Normal path\n");
        fail(42);
    } else if (err == 42) {
        printf("Caught error code 42\n");
    } else {
        printf("Unknown error %d\n", err);
    }

    return 0;
}

How It Works

  1. Save the return value. err = setjmp(env) is 0 on the first visit.
  2. Normal path. Print a message, then call fail(42).
  3. Jump with a code. longjmp(env, 42) makes setjmp return 42.
  4. Do not use 0 as a code. If you pass 0, the standard makes setjmp return 1 instead—so reserve 0 for “first visit only.”

Example 3 — Prefer Return Codes for Normal Errors

Same divide problem without longjmp—clearer for beginners and safer with cleanup. Pair with errno when wrapping library calls.

C
#include <stdio.h>

int safe_divide(int a, int b, int *out) {
    if (b == 0) {
        return -1;   /* recoverable error */
    }
    *out = a / b;
    return 0;
}

int main(void) {
    int result;

    if (safe_divide(10, 2, &result) == 0) {
        printf("Result: %d\n", result);
    }

    if (safe_divide(10, 0, &result) != 0) {
        printf("Error: Division by zero!\n");
    }

    printf("Program continues after recovery\n");
    return 0;
}

How It Works

  1. Check before divide. b == 0 returns -1 without crashing or jumping.
  2. Write through a pointer. On success, store a / b in *out and return 0.
  3. Caller decides. main prints the result or an error message—stack and locals stay normal.
  4. When to still learn setjmp. Useful for interpreters or parsers that need a deep “bail out”; not for ordinary validation.

Edge Cases & Pitfalls

Check these before using setjmp / longjmp in real projects.

lifetime

Never jump to a returned function

If the function that called setjmp already returned, that jmp_buf is invalid. Using it is undefined behavior.

locals

Use volatile after a jump

Non-volatile locals in the setjmp function may be stale or wrong after longjmp.

cleanup

Skips normal cleanup

longjmp does not call fclose or free. Clean up resources before jumping, or leak them.

val

Do not pass 0 as the code

longjmp(env, 0) still makes setjmp return 1. Use distinct non-zero codes for errors.

Performance Notes

ApproachCostBest for
setjmp (no jump)Small save of registers / contextRare entry to a protected region
longjmpRestores context; skips stack framesDeep bail-out paths
Return codesCheapest and clearestAlmost all application errors

Performance is rarely why people choose setjmp. Correctness, cleanup, and readability matter more—default to returns, then escalate only when a deep unwind is truly needed.

Key Takeaways

  • Role: non-local jump via jmp_buf, setjmp, longjmp.
  • Returns: first setjmp → 0; after jump → your code (not 0).
  • Safety: valid bookmark only; use volatile for locals.
  • Default: prefer return codes over longjmp.

One line: setjmp plants a bookmark; longjmp reopens it—powerful across functions, dangerous if the bookmark is gone.

Frequently Asked Questions

setjmp.h provides setjmp and longjmp for non-local jumps: save the current execution context in a jmp_buf with setjmp, then later jump back to that point with longjmp—like a time machine for your call stack, but with strict rules.
On the first direct call, setjmp returns 0. When longjmp jumps back, setjmp returns again with the val argument you passed to longjmp—unless val is 0, in which case setjmp returns 1 instead.
Similar idea (jump elsewhere) but different scope. goto only moves within one function. setjmp/longjmp can unwind across function calls—but only to a still-active setjmp in the same call chain. Misuse breaks the stack.
Only volatile locals are guaranteed to keep meaningful values after longjmp. Other locals may be corrupted or stale. Never longjmp past a function that has returned—the jmp_buf becomes invalid.
Usually no. Prefer return codes, errno, and normal cleanup. setjmp/longjmp skip fclose and free unless you clean up manually. Reserve them for parsers, interpreters, or legacy patterns—not everyday validation errors.
Yes, if setjmp was called in an ancestor that is still active (has not returned). longjmp cannot jump into a setjmp in a function that already returned—that jmp_buf is undefined to use.

Next: signal.h

Learn how C programs handle asynchronous signals.

signal.h tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful