- C标准库
- C库 - 首页
- C库 - <assert.h>
- C库 - <complex.h>
- C库 - <ctype.h>
- C库 - <errno.h>
- C库 - <fenv.h>
- C库 - <float.h>
- C库 - <inttypes.h>
- C库 - <iso646.h>
- C库 - <limits.h>
- C库 - <locale.h>
- C库 - <math.h>
- C库 - <setjmp.h>
- C库 - <signal.h>
- C库 - <stdalign.h>
- C库 - <stdarg.h>
- C库 - <stdbool.h>
- C库 - <stddef.h>
- C库 - <stdio.h>
- C库 - <stdlib.h>
- C库 - <string.h>
- C库 - <tgmath.h>
- C库 - <time.h>
- C库 - <wctype.h>
C库宏 - setjmp()
C库宏setjmp() 将当前的环境保存到变量environment中,以便稍后由函数longjmp()使用。如果该宏直接从宏调用返回,则返回零;如果它从longjmp()函数调用返回,则返回传递给longjmp作为第二个参数的值。
此函数用于在C中实现异常处理。
语法
以下是C库宏setjmp()的语法:
setjmp(jmp_buf environment)
参数
此函数只接受一个参数:
- environment - 这是jmp_buf类型的对象,其中存储环境信息。
返回值
此宏可能多次返回。第一次,在其直接调用时,它总是返回零。当longjmp使用设置为environment的信息调用时,宏再次返回;现在它返回传递给longjmp作为第二个参数的值。
示例1
以下是一个基本的C程序,它显示了setjmp()函数的使用方法。
#include <setjmp.h>
#include <stdio.h>
jmp_buf buf;
void func()
{
printf("Welcome to Tutorialspoint\n");
// Jump to the point setup by setjmp
longjmp(buf, 1);
printf("Python Tutorial\n");
}
int main()
{
// Setup jump position using buf and return 0
if (setjmp(buf))
printf("Java Tutorial\n");
else {
printf("The else-statement printed\n");
func();
}
return 0;
}
输出
以上代码产生以下结果:
The else-statement printed Welcome to Tutorialspoint Java Tutorial
示例2
在这个例子中,我们演示了函数longjmp()和setjmp()的标准调用和返回序列。
#include <stdio.h>
#include <setjmp.h>
#include <stdnoreturn.h>
jmp_buf my_jump_buffer;
noreturn void foo(int status)
{
printf("foo(%d) called\n", status);
longjmp(my_jump_buffer, status + 1);
}
int main(void)
{
volatile int count = 0;
if (setjmp(my_jump_buffer) != 5)
foo(++count);
return 0;
}
输出
执行上述代码后,我们得到以下结果:
foo(1) called foo(2) called foo(3) called foo(4) called
示例3
以下是setjmp()函数的另一个示例。
#include <stdio.h>
#include <setjmp.h>
#include <stdlib.h>
int a(char *s, jmp_buf env) {
int i;
i = setjmp(env);
printf("Setjmp returned %d\n", i);
printf("S = %s\n", s);
return i;
}
int b(int i, jmp_buf env) {
printf("In b: i = %d, Calling longjmp\n", i);
longjmp(env, i);
}
int main() {
jmp_buf env;
if (a("Tutorial", env) != 0)
exit(0);
b(3, env);
return 0;
}
输出
执行上述代码后,我们得到以下结果:
Setjmp returned 0 S = Tutorial In b: i = 3, Calling longjmp Setjmp returned 3 S = ��UH��H���
广告