#include<stdio.h>
#include<setjmp.h>
jmp_buf ebuf;
int func();
int main(){
int i;
printf("1111/n");
i = setjmp(ebuf);
printf("%d/n",i);
if(i==0){
func();
printf("this will not be printed");
}
if(i==3){
printf("3333/n");
}
printf("%d/n",i);
return 0;
}
int func(){
printf("2222/n");
longjmp(ebuf,3);
}
輸出結果:
1111
0
2222
3
3333
3
相當與goto語句,當執行func函數時,由longjmp跳轉到setjmp處,然後再往下執行。
注意的地方:longjmp(dbuf,val)其中的val不能爲0,如果爲0則系統默認再i=setjmp(ebuf)中i的返回值爲1;
以下函數實現了多個函數之間的跳轉,其中具體代碼在 動態調用鏈接庫中
#include <stdio.h>
#include <windows.h>
#include <setjmp.h>
jmp_buf ebuf;
int jump1();
int jump2();
int i;
main(){
i = setjmp(ebuf);
if(i==0|i==2){
jump1();
}
if(i==1){
jump2();
}
}
int jump1(){
while(1){
HINSTANCE hInstance;
void (*func)();
hInstance = LoadLibrary("my.dll");
showGUI();
char s[10];
scanf("%s",&s);
func = ( void (*)() )GetProcAddress(hInstance,s);
if(!func){
longjmp(ebuf,1);
}
(*func)();
continue;
}
}
int jump2(){
printf("your input is wrong/n");
longjmp(ebuf,2);
}
int showGUI(){
FILE *login;
char c;
login = fopen("login.txt","r");
if(!login){
printf("file err:login/n");
return;
}
while(1){
c = fgetc(login);
if(c == EOF){
break;
}
printf("%c",c);
}
fclose(login);
return 0;
}