C基礎(chǔ)(C語言中的錯(cuò)誤處理)

字號(hào):

#include
    #include
    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);
    }
    輸出結(jié)果:
    1111
    0
    2222
    3
    3333
    3
    相當(dāng)與goto語句,當(dāng)執(zhí)行func函數(shù)時(shí),由longjmp跳轉(zhuǎn)到setjmp處,然后再往下執(zhí)行。
    考試大提示注意的地方:longjmp(dbuf,val)其中的val不能為0,如果為0則系統(tǒng)默認(rèn)再i=setjmp(ebuf)中i的返回值為1;
    以下函數(shù)實(shí)現(xiàn)了多個(gè)函數(shù)之間的跳轉(zhuǎn),其中具體代碼在 動(dòng)態(tài)調(diào)用鏈接庫中
    #include
    #include
    #include
    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;
    }