#include <setjmp.h> #include <stdio.h> #include <stdlib.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 volaval; static int statval; globval = 1; autoval = 2; regival = 3; volaval = 4; statval =5; //使用了ISO C字符串的自动连接 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 = 95; autoval = 96; regival = 97; volaval = 98; statval = 99; f1( autoval, regival, volaval, statval ); exit( 0 ); } void f1( int i, int j, int k, int l ) { printf( "in fl!\n" ); printf( "globval = %d, autoval = %d, regival = %d, volaval = %d, statval = %d\n ",globval, i, j, k, l ); f2(); } void f2() { printf( "in f2!\n" ); longjmp( jmpbuffer, 1 ); }
不进行优化的运行结果如下:
wangkai@ubuntu:~/Test$ cc getuid.c wangkai@ubuntu:~/Test$ ./a.out in fl! globval = 95, autoval = 96, regival = 97, volaval = 98, statval = 99 in f2! after longjmp: globval = 95, autoval = 96, regival = 97, volaval = 98, statval = 99 wangkai@ubuntu:~/Test$
进行全部优化的编译
wangkai@ubuntu:~/Test$ cc -O getuid.c wangkai@ubuntu:~/Test$ ./a.out in fl! globval = 95, autoval = 96, regival = 97, volaval = 98, statval = 99 in f2! after longjmp: globval = 95, autoval = 2, regival = 3, volaval = 98, statval = 99