typestar

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

  1. setjmp returns zero when it saves, non-zero when jumped to.
  2. longjmp unwinds without running any cleanup.
  3. Locals that must survive it should be volatile.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 2 in Escape hatches, step 12 of 13 in Unions, bitfields & undefined behavior.

← Previous Next →