C语言之setjmp

#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原型

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值