C Non-local Jumps

Definition
What Is a Non-local Jump in C?
A non-local jump lets a program leave deep call frames and resume at an earlier setjmp() point. The <setjmp.h> header provides that pattern with setjmp(), longjmp(), and the jmp_buf type.
Think of setjmp() as saving a bookmark and longjmp() as jumping back to it. The jump skips normal returns, so you must keep the rules simple and clean up carefully.
Key idea.
Learn the save-and-jump pattern, then prefer ordinary return codes for everyday errors.
Building blocks
The Three Parts
| Part | Role |
|---|---|
jmp_buf | Storage for the saved calling environment. |
setjmp() | Saves the bookmark and returns 0 on the first pass. |
longjmp() | Restores the bookmark and makes setjmp() return again. |
Pattern
The Save and Jump Pattern
- Declare a jmp_buf. This holds the saved environment.
- Call setjmp(). On the first pass it returns 0.
- Do normal work. If something must abort early, call longjmp().
- Handle the jump path. When setjmp() returns nonzero, run recovery code.
Example
Starter: Save, Jump, and Resume
C
#include <stdio.h>
#include <setjmp.h>
int main(void) {
jmp_buf env;
int code = setjmp(env);
if (code == 0) {
printf("first pass\n");
longjmp(env, 3);
}
printf("resumed with %d\n", code);
return 0;
} How It Works
- Save the environment.
setjmp(env)returns 0 the first time. - Take the first branch. The program prints
first pass. - Jump with longjmp(). Control returns through
setjmp()again. - Read the new value.
codebecomes 3 and the resume line prints.
Next steps
Open the Function Guides
Frequently Asked Questions
It is a jump back to an earlier active setjmp() call using longjmp(), instead of returning through every function one by one.
jmp_buf is the type that stores the calling environment saved by setjmp().
setjmp() returns 0 the first time. After longjmp(), it returns a nonzero value.
Learn setjmp() to save a bookmark, then longjmp() to jump back.
Usually no. Prefer return codes. Use setjmp/longjmp only when a special recovery path is worth the extra rules.
Browse setjmp.h functions
Open setjmp() and longjmp() with full examples.
8 people found this page helpful
