#include <stdio.h>
#include <stdlib.h>
#include <setjmp.h>
static jmp_buf buf;
int main(void)
{
volatile int b = 3;
if (setjmp(buf) != 0)
{
printf("%d\n", b);
exit(0);
}
b = 5;
longjmp(buf, 1);
return 0;
}
Answer: 5
The setjmp
function stores context information for a “non-local goto”, and returns 0. Thelongjmp
function transfers control to the
setjmp
call that initializedbuf
, and execution continues from this point as if
setjmp
had returned 1.
Note: a non-volatile automatic variable that has been modified after setjmp
becomes indeterminate afterlongjmp
. Without the
volatile
qualifier, this program’s behavior would be undefined. This rule permits better optimization of code.
关键点在于理解setjmp以及longjmp,(http://en.wikipedia.org/wiki/Setjmp.h )第一次运行到setjmp,会设置jmp_buf,然后返回0。当调用longjmp时,会把longjmp里面的非0值作为setjmp的返回值返回(如果longjmp的value参数为0,setjmp恢复后返回1,也就是当恢复到setjmp存储点的时候,setjmp一定不会返回0)。——Veda原型