非局部跳转 (setjmp, longjmp)

异常处理

#include <setjmp.h>

//setjmp 记住当前位置,
//longjmp 可以从任意深度的调用中返回到那里:
//这是 C 中最接近 throw 和 catch 的机制
static jmp_buf onError;

int divide(int a, int b) {
    if (b == 0) {
        longjmp(onError, 1); //setjmp 现在“返回”1
    }
    return a / b;
}

//setjmp 之后被修改的局部变量,
//跳转后只有声明为 volatile 才能保持其值
volatile int result = 0;

//setjmp 第一次返回 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");
}
//输出 "division by zero"
//result is 5

//跳转会跳过途中每个函数的剩余部分:
//它们分配的内存不会被释放,文件不会被关闭。
//setjmp 只能出现在条件中,不能出现在赋值中

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