capypad
0 day streak
c / expert
Snippet

Non-local Jumps with setjmp and longjmp

setjmp and longjmp provide a way to perform non-local jumps, bypassing the normal function return mechanism. setjmp saves the execution environment (stack pointer, program counter), and longjmp restores it, essentially allowing a 'try-catch' behavior in C. Note that local variables in the calling function might have indeterminate values if modified between setjmp and longjmp.

snippet.c
c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <setjmp.h>
jmp_buf env;
 
void deep_nesting() {
if (error_occurred) longjmp(env, 1);
}
 
int main() {
if (setjmp(env) == 0) {
// Normal execution path
deep_nesting();
} else {
// Exception handling path
printf("Recovered from deep error\n");
}
return 0;
}
Breakdown
1
jmp_buf env;
A buffer to store the processor state and environment information.
2
if (setjmp(env) == 0)
Initial call returns 0. If returned via longjmp, it returns the value passed to longjmp.
3
longjmp(env, 1);
Restores the environment saved in 'env', causing setjmp to return 1.