测试 setjmp 和 longjmp 的用法

来源:互联网 发布:python idle打不开 编辑:程序博客网 时间:2024/06/15 18:16

C语言goto是不能跨函数的原因跨函数需要保存现场回来需要恢复现场.

setjmp 和 longjmp 配合可以实现在C语言程序中跨函数跳转.


M$给的例子, 对于测试setjmp和longjmp整的复杂了.

我写了一个简单明了的测试程序, 只测试 setjmp和longjmp.

/// @file ClassroomExamples.c/// @brief xxxx-xxxx课堂笔记的验证代码/// 测试 setjmp 和 longjmp 的用法#include <stdlib.h>#include <stdio.h>#include <stddef.h>#include <crtdbg.h>#include <conio.h>#include <setjmp.h>void fnTest1();void fnTest2();jmp_buf g_mark_goto_addr; /* Address for long jump to jump to */int g_jmpret = -2;int main(int argc, char *argv[ ], char *envp[ ]){    do     {        fnTest1();        fnTest2();        printf("if need quit, press 'q'\r\n");        if ('q' == _getch())        {            break;        }    } while (1);        printf("END, press any key to quit\n");    getchar();        return 0;}void fnTest1(){    int jmpret = 0;        printf(">> fnTest1()\n");        if (0 != g_jmpret)    {        // setjmp 和 longjmp 配合使用一次后, 就失效了        // 需要重新执行setjmp, 然后才能重新longjmp        // 暂时还没想到实际引用longjmp的场景        // 以后看看longjmp在实际场景中怎么用        g_jmpret = setjmp(g_mark_goto_addr);        if (-1 != g_jmpret)        {            printf("env save ok\r\n");        }    }        printf("<< fnTest1()\n");}void fnTest2(){    int iKeyIn = 0;    printf(">> fnTest2()\n");        printf("if want longjmp to fnTest1, press y:");    iKeyIn = _getch();    if ('y' == iKeyIn)    {        if (-1 != g_jmpret)        {            printf("longjmp to fnTest1 ^_^\n");                        /* Restore calling environment and jump back to setjmp. Return             * -1 so that setjmp will return false for conditional test.            */            longjmp(g_mark_goto_addr, -1);        }    }        printf("<< fnTest2()\n");}



0 0