diff --git a/02-setjmp/jmp.c b/02-setjmp/jmp.c new file mode 100644 index 0000000..6cd83b4 --- /dev/null +++ b/02-setjmp/jmp.c @@ -0,0 +1,26 @@ +#include +#include + +jmp_buf env; + +void second() { + printf("Inside second function\n"); + longjmp(env, 1); // 跳回setjmp的地方,并且setjmp返回1 +} + +void first() { + printf("Inside first function\n"); + second(); + printf("This line will not be printed\n"); // 不会执行到这里 +} + +int main() { + if (setjmp(env) == 0) { + // 第一次调用setjmp时返回0 + first(); + } else { + // 从longjmp返回时,setjmp将返回非零值 + printf("Back to main\n"); + } + return 0; +} \ No newline at end of file