<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
Plant a bookmark with setjmp, run work, and jump back with longjmp only while that bookmark is still valid.
Add #include <setjmp.h> and declare a jmp_buf (often file-scope or passed by pointer).
Call setjmp(env): first return is 0—run the protected code.
On failure deep in the call chain, call longjmp(env, code) with a non-zero code.
Handle the non-zero return from setjmp in an else (or switch) branch.
Piece
Required?
Role
jmp_buf env
Yes
Stores the saved execution context
setjmp(env)
Yes
Saves context; returns 0, then later the jump code
longjmp(env, val)
On error path
Restores 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
Reference
Cheat Sheet
Keep these facts handy while studying non-local jumps.
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
Trace
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
Code
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;
}
Output
Result: 5
Error: Division by zero!
Program continues after recovery
How It Works
First visit.setjmp(env) returns 0, so the if branch runs.
Success path.divide(10, 2) prints Result: 5.
Jump.divide(10, 0) calls longjmp(env, 1)—control returns to setjmp with value 1.
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.
Save the return value.err = setjmp(env) is 0 on the first visit.
Normal path. Print a message, then call fail(42).
Jump with a code.longjmp(env, 42) makes setjmp return 42.
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;
}
Output
Result: 5
Error: Division by zero!
Program continues after recovery
How It Works
Check before divide.b == 0 returns -1 without crashing or jumping.
Write through a pointer. On success, store a / b in *out and return 0.
Caller decides.main prints the result or an error message—stack and locals stay normal.
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.
Analysis
Performance Notes
Approach
Cost
Best for
setjmp (no jump)
Small save of registers / context
Rare entry to a protected region
longjmp
Restores context; skips stack frames
Deep bail-out paths
Return codes
Cheapest and clearest
Almost 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.
Remember
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.