#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;


#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)


#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;
}