- 论坛徽章:
- 0
|
回答学习要点06中“全局跳转”问题<红色标记>:
我重新阅读了APUE中关于setjmp的章节,截出关于该问题的解答:
"what are the states of the automatic variables and register variables in the main function?" When main is returned to by the longjmp, do these variables have values corresponding to when the setjmp was previously called, or are their values left alone so that their values left alone so that their values are whatever they were when do_line was called? Unfortunately, the answer is "it depends."
下面以一个实例看下具体情况:
代码:
- #include <setjmp.h>
- #include <stdio.h>
- static void f1(int, int, int, int);
- static void f2(void);
- static jmp_buf jmpbuffer;
- static int globval;
- int main(void)
- {
- int autoval;
- register int regival;
- volatile int volaval;
- static int statval;
- globval = 1;
- autoval = 2;
- regival = 3;
- volaval = 4;
- statval = 5;
- if(setjmp(jmpbuffer) != 0){
- printf("after longjmp: \n");
- printf("globval = %d, autoval = %d, regival = %d, volaval = %d, statval = %d\n", globval, autoval, regival, volaval, statval);
- exit(0);
- }
- globval = 91;
- autoval = 92;
- regival = 93;
- volaval = 94;
- statval = 95;
- f1(autoval, regival, volaval, statval);
- exit(0);
- }
- static void f1(int i, int j, int k, int l){
- printf("in f1():\n");
- printf("globval = %d, autoval = %d, regival = %d, volaval = %d, statval = %d\n", globval, i, j, k, l);
- f2();
- }
- static void f2(void){
- longjmp(jmpbuffer, 1);
- }
复制代码
下面是在Red Hat9上的运行结果:
代码:
- [bill@billstone Unix_study]$ uname -a
- Linux billstone 2.4.20-8 #1 Thu Mar 13 17:18:24 EST 2003 i686 athlon i386 GNU/Linux
- [bill@billstone Unix_study]$ ./testjmp
- in f1():
- globval = 91, autoval = 92, regival = 93, volaval = 94, statval = 95
- after longjmp:
- globval = 91, autoval = 92, regival = 93, volaval = 94, statval = 95
- [bill@billstone Unix_study]$
复制代码
在Ubuntu上的测试结果:
代码:
- billstone@ubuntu:~/Unix_C$ uname -a
- Linux ubuntu 2.6.24-22-generic #1 SMP Mon Nov 24 19:35:06 UTC 2008 x86_64 GNU/Linux
- billstone@ubuntu:~/Unix_C$ ./testjmp
- in f1():
- globval = 91, autoval = 92, regival = 93, volaval = 94, statval = 95
- after longjmp:
- globval = 91, autoval = 92, regival = 93, volaval = 94, statval = 95
- billstone@ubuntu:~/Unix_C$
复制代码
可以看到在这两个系统上setjmp并没有将自动变量和寄存器变量回复到之前的状态。
大家如果使用着其他系统,请测试一下并将结果发上来一起探讨。 |
|