longjmp是一个C标准库函数,用于在程序中执行跳转。它的作用是使程序从当前的执行状态直接跳转到之前调用setjmp()函数处,并且继续执行后面的代码。
它通常和setjmp()函数一起使用。在使用时,我们先调用setjmp()函数,将当前的执行状态保存下来;然后在某个条件成立时调用longjmp()函数,就会直接跳转到之前调用setjmp()处,并从那里开始执行代码。
以下是一个简单的示例:
#include <stdio.h>
#include <stdlib.h>
#include <setjmp.h>
static jmp_buf env;
void test_func() {
    printf("enter test_func\n");
    longjmp(env, 1);
}
int main() {
    if(setjmp(env) == 0) {
        printf("first time setjmp()\n");
        test_func();
    } else {
        printf("long jump from test_func()\n");
    }
    return 0;
}
运行上述程序会输出以下内容:
first time setjmp()
enter test_func
long jump from test_func()
首次调用setjmp()会返回0,并且打印“first time setjmp()”信息。然后我们调用了test_func()函数,在该函数中调用了longjump(),并传入了env和值1。这导致程序回到了原始环境(即第一次调用setjump()处),并且打印了“long jump from test_func()”。


 
                             
         
        
 
         
         
         
         
         
         
        
 
                 
                 
                 
                 
                 
                 
                 
                 
                