nsetjmp和longjmp函数实现函数之间的跳转(需包含头文件"setjmp.h"):
函数原型:int setjmp(jmp_buf env);
void longjmp(jmp_buf env, int val);
setjmp函数用于设置跳转的目的位置,longjmp函数进行跳转。
env:保留了需要返回的位置的堆栈情况。
setjmp的返回值:直接调用该函数,则返回0;若由longjmp的调用,导致setjmp被调用,则返回val(longjmp的第二个参数)。
1.longjmp对各类型参数的影响:
考虑下面这个程序:
#include<iostream>#include<setjmp.h>#include<stdlib.h>#include<stdio.h>using namespace std;jmp_buf jmpbuffer;void g(){ cout << "in g()" << endl; longjmp(jmpbuffer, 2);}void f(){ cout << "in f()" << endl; g(); cout << "leave f()" << endl;}int globval;int main(){ int autoval; register int regival; volatile int volaval; static int statval; cout << "begin" << endl; globval = 90; autoval = 91; regival = 92; volaval = 93; statval = 94; int i = setjmp(jmpbuffer); cout << "setjmp return code: " << i << endl; if(2 == i) { cout << "error code: "<< i << endl; cout << "globval= " << globval << "; "; cout << "autoval= " << autoval << "; "; cout << "regival= " << regival << "; "; cout << "volaval= " << volaval << "; "; cout << "statval= " << statval << "; " << endl; return 0; } globval = 0; autoval = 1; regival = 2; volaval = 3; statval = 4; cout << "globval= " << globval << "; "; cout << "autoval= " << autoval << "; "; cout << "regival= " << regival << "; "; cout << "volaval= " << volaval << "; "; cout << "statval= " << statval << "; " << endl; f(); return 0;}在编译时禁止优化,输出结果如下:
使用O3优化编译,结果如下:
在非优化时,包括寄存器变量(register修饰)在内的所有类型都被存放在内存中,所以所有变量都是更改后的值。
在优化编译时,自动变量(默认类型)和寄存器变量被存储在寄存器中,其它变量与非优化时一样。所以autoval和regival都还原为原来的值。
附jmp_buf结构:
§
typedef struct { unsigned j_sp; // 堆栈指针寄存器 unsigned j_ss; // 堆栈段 unsigned j_flag; // 标志寄存器 unsigned j_cs; // 代码段 unsigned j_ip; // 指令指针寄存器 unsigned j_bp; // 基址指针 unsigned j_di; // 目的指针 unsigned j_es; // 附加段 unsigned j_si; // 源变址 unsigned j_ds; // 数据段 } jmp_buf;
保证局部变量在longjmp过程中一直保存它的值的方法:把它声明为volatile变量。(适合那些在setjmp执行和longjmp返回之间会改变的变量)。
存放在内存中的变量,将具有调用longjmp时的值,而在CPU和浮点寄存器中的变量则恢复为调用setjmp函数时的值。
优化编译时,register和auto变量都存放在寄存器中,而volatile变量仍存放在内存。
2.用setjmp和longjmp实现C++异常处理(try/catch)
View Code
#include<setjmp.h>jmp_buf jmpbuffer;#define try \ int jmp; \ jmp = setjmp(jmpbuffer); \ if(0 == jmp) \#define throw(a) longjmp(jmpbuffer, a);#define catch(a) \ a = jmp; \ if(0 != jmp)
测试(.c文件):
View Code
#include"head.h"#include<setjmp.h>#include<stdlib.h>#include<stdio.h>void g(){ printf("in g()\n"); throw(32);}void f(){ printf("in f()\n"); g(); printf("leave f()\n");}int main(){ printf("begin\n"); try { f(); } catch(int a) { printf("in catch: %d\n", a); } return 0;}
来源:https://www.cnblogs.com/lq0729/archive/2011/10/23/2222117.html