What is setjmp and longjmp in C: Simple Explanation and Example
setjmp and longjmp are C functions used for non-local jumps, allowing a program to jump back to a saved point in the code. setjmp saves the current environment (like a bookmark), and longjmp jumps back to that saved point, restoring the environment.How It Works
Imagine you are reading a book and you put a bookmark on a page so you can return to it later. In C, setjmp acts like placing that bookmark by saving the current state of the program, including where it is in the code and the values of some variables.
Later, if something unusual happens, you can use longjmp to jump back to the bookmark, skipping any code in between. This lets the program recover or handle errors without going step-by-step through all the code.
Under the hood, setjmp saves the program's stack context, and longjmp restores it, making the program continue as if it just returned from setjmp.
Example
This example shows how setjmp saves a point and longjmp jumps back to it after an error is detected.
#include <stdio.h> #include <setjmp.h> jmp_buf buf; void second() { printf("Inside second function. Jumping back to main.\n"); longjmp(buf, 1); // Jump back to where setjmp was called } void first() { printf("Inside first function. Calling second.\n"); second(); printf("This line will not run.\n"); } int main() { if (setjmp(buf) == 0) { printf("Calling first function.\n"); first(); } else { printf("Back in main after longjmp.\n"); } return 0; }
When to Use
setjmp and longjmp are useful when you want to handle errors or unusual situations that happen deep inside nested function calls without returning through every function manually.
For example, they can be used in error handling in embedded systems, parsing complex data, or recovering from unexpected conditions where normal return paths are complicated.
However, they should be used carefully because jumping around can make code harder to understand and maintain.
Key Points
setjmpsaves the current program state.longjmpjumps back to the saved state.- They enable non-local jumps, skipping normal function returns.
- Useful for error handling and recovery.
- Use with caution to keep code clear and safe.
Key Takeaways
setjmp saves a program state to return to later.longjmp jumps back to the saved state, restoring it.