C语言中的setjump()和longjump()

在本节中,我们将看到什么是C中的setjump和跳远踏板setjump()longjump()位于SETJMP.H库。这两个函数的语法如下。

setjump(jmp_buf buf) : uses buf to store current position and returns 0.
longjump(jmp_buf buf, i) : Go back to place pointed by buf and return i.

这些在C中用于异常处理。该setjump()可作为try块,并且longjump()可以作为throw语句。该longjump()转移控制由指向的足尖setjump()

在这里,我们将看到如何在不使用递归,循环或宏扩展的情况下将数字打印100次。在这里,我们将使用setjump()longjump()方法。

示例

#include <stdio.h>
#include <setjmp.h>
jmp_buf buf;
main() {
   int x = 1;
   setjmp(buf); //set the jump position using buf
   printf("5"); // Prints a number
   x++;
   if (x <= 100)
      longjmp(buf, 1); // Jump to the point located by setjmp
}

输出结果

5555555555555555555555555555555555555555555555555555555555555555555555555555
555555555555555555555555