setjmp and longjmp in C
A non-local jump back to a saved point — C's closest thing to an exception.
#include <setjmp.h>
#include <stdio.h>
static jmp_buf recovery;
static void deep(int depth) {
if (depth > 2) {
longjmp(recovery, 42);
}
deep(depth + 1);
}
int attempt(void) {
volatile int attempts = 0;
int code = setjmp(recovery);
if (code != 0) {
printf("recovered with %d after %d attempt(s)\n", code, attempts);
return code;
}
attempts++;
deep(0);
return 0;
}
How it works
setjmpreturns zero when it saves, non-zero when jumped to.longjmpunwinds without running any cleanup.- Locals that must survive it should be
volatile.
Keywords and builtins used here
attemptdeepifintjmp_bufreturnstaticvoidvolatile
The run, in numbers
- Lines
- 24
- Characters to type
- 366
- Tokens
- 98
- Three-star pace
- 110 tpm
At the three-star pace of 110 tokens a minute, this run takes about 53 seconds.
Step 2 of 2 in Escape hatches, step 12 of 13 in Unions, bitfields & undefined behavior.