#include <stdio.h>
#include <setjmp.h>
#include <stdbool.h>
static jmp_buf g_env;
static volatile int g_after_longjmp_reached = 0;
static void jump_with_code(int code) {
longjmp(g_env, code);
g_after_longjmp_reached = 1;
}
int main(void) {
volatile int step = 0;
int rc1 = setjmp(g_env);
if (rc1 == 0) {
step = 1;
jump_with_code(1);
} else {
step += 10;
}
bool c1_pass = (rc1 == 1 && step == 11 && g_after_longjmp_reached == 0);
int rc2 = setjmp(g_env);
if (rc2 == 0) {
jump_with_code(0);
}
bool c2_pass = (rc2 == 1 && g_after_longjmp_reached == 0);
volatile int counter = 10;
int rc3 = setjmp(g_env);
if (rc3 == 0) {
counter += 5;
jump_with_code(42);
}
bool c3_pass = (rc3 == 42 && counter == 15);
printf(
"{"
"\"runtime\":\"GCC C11 (mstorsjo/llvm-mingw:20260616)\","
"\"cases\":["
"{\"name\":\"setjmp_longjmp_basic_flow\",\"expected\":\"rc=1,step=11,skip=0\",\"actual\":\"rc=%d,step=%d,skip=%d\",\"passed\":%s},"
"{\"name\":\"longjmp_zero_becomes_one\",\"expected\":1,\"actual\":%d,\"passed\":%s},"
"{\"name\":\"volatile_local_preserved_across_jump\",\"expected\":\"rc=42,counter=15\",\"actual\":\"rc=%d,counter=%d\",\"passed\":%s}"
"]"
"}\n",
rc1, (int)step, (int)g_after_longjmp_reached, c1_pass ? "true" : "false",
rc2, c2_pass ? "true" : "false",
rc3, (int)counter, c3_pass ? "true" : "false"
);
return 0;
}
本例需在 本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,GCC C11 linux/amd64,--network none)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,GCC C11 linux/amd64,--network none)。
入口文件:projects/c-standard-library-setjmp-h-lab/explore-standard-library-setjmp-h.c
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-standard-library-setjmp-h.c,或下载右侧课程工程包。 - 确认本地已准备 本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,GCC C11 linux/amd64,--network none)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联63章) · 含当前章节或实例 · mbskycom202612a3210.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3250.zip