zoukankan      html  css  js  c++  java
  • C Snippet——使用setjmp()和longjmp()函数模拟C++中的try和catch

    使用setjmp()和longjmp()函数模拟C++中的try和catch

    #include<stdio.h>
    #include<setjmp.h>
    #include<stdlib.h>
    
    
    #define try if (!(ret = setjmp(buf)))
    #define catch(i) else
    #define throw(i) longjmp(buf, i)
    
    
    jmp_buf buf;
    
    
    void sub1()
    {
        printf("in sub1()
    ");
        throw(1);   //longjmp(buf, 1)
        printf("you will never see this!");
    }
    void sub2()
    {
        printf("in sub2()
    ");
        throw(2);  //longjmp(buf, 2)
        printf("you will never see this!");
    }
    extern int setjmp_execute()
    {
        int ret;
        try   //if (!(ret = setjmp(buf))) 即 setjmp(buf)的返回值为0
        {
            printf("first time through
    ");
            sub1();
            sub2();
        }
        catch(ret)  //else
        {
            switch(ret)
            {
                case 1:
                    printf("sub1 raised an exception
    ");
                    break;
                case 2:
                    printf("sub2 raised an exception
    ");
                    break;
                default:
                    break;
            }
        }
        printf("back in main()
    ");
        
        system("pause");
    
        return 0;
    }
  • 相关阅读:
    hdu 1286
    hdu 1420
    hdu 2068
    hdu 1718
    hdu 1231
    hdu 1072
    HDOJ 350留念
    hdu 1898
    hdu 1593
    帮助理解git的图
  • 原文地址:https://www.cnblogs.com/mjjackey/p/13812209.html
Copyright © 2011-2022 走看看