<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.
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; }