Non-local jumps (setjmp, longjmp)

Exception handling

#include <setjmp.h>

//setjmp remembers the place, longjmp returns there from any depth
//of calls: the nearest thing to throw and catch in C
static jmp_buf onError;

int divide(int a, int b) {
    if (b == 0) {
        longjmp(onError, 1); //setjmp now "returns" 1
    }
    return a / b;
}

//a local variable changed after setjmp keeps its value
//after the jump only if it is volatile
volatile int result = 0;

//the first time setjmp returns 0
if (setjmp(onError) == 0) {
    //try
    result = divide(10, 2);
    result = divide(1, 0);
    printf("not printed\n");
} else {
    //catch
    printf("division by zero\n");
}
//printed "division by zero"
//result is 5

//the jump skips the rest of every function on the way:
//memory they allocated is not freed, files are not closed.
//setjmp may stand only in a condition, not in an assignment

printf("result is %d\n", result);