在C语言中,goto语句不能跨越函数。setjmp和longjmp可以完成。
1.#include "apue.h"
2 #include <setjmp.h>
3
4 static void f1(int, int, int, int);
5 static void f2(void);
6
7 static jmp_buf jmpbuffer;
8 static int globval;
9
10 //#ifdef UNMAIN
11 int
12 main(void)
13 {
14 int autoval;
15 register int regival;
16 volatile int volaval;
17 static int statval;
18
19 globval = 1; autoval = 2; regival =4; volaval = 4; statval = 5;
20 if(setjmp(jmpbuffer) != 0){
21 printf("after longjmp: \n");
22 printf("globval = %d, autoval = %d, regival = %d,"
23 "volaval = %d, statval = %d \n",
24 globval, autoval, regival, volaval, statval);
25 exit(0);
26 }
27
28 /*
29 * change variables after setjmp, but before longjmp .
30 */
31 globval = 95; autoval = 96; regival = 97; volaval = 98; statval = 99;
32 f1(autoval, regival, volaval, statval); /*never returns*/
33 exit(0);
34 }
35
36 static void
37 f1(int i, int j, int k, int l)
38 {
39 printf("in fl() \n");
40 printf("globval = %d, autoval = %d, regival = %d,"
41 "volval = %d, statval = %d\n", globval, i, j, k, l);
42 f2();
43 }
44 static void
45 f2(void)
46 {
47 longjmp(jmpbuffer, 1);
48 }
如代码,如果要编写一个使用非局部跳转的可移植程序,则必须使用volatile属性。autoval和regival都存放在寄存器中,volatile变量则存放在存储器中。
引用:UNIX环境高级编程的7.10
注:第一次试着写自己觉得重要的内容,网上没有查到的内容。