longjmp setjmp and volatile

 1 /*******************************************************************************
 2 * 版权所有:
 3 * 模 块 名:
 4 * 文 件 名:volatile_setjmp.c
 5 * 实现功能:
 6 * 作    者:XYZ
 7 * 版    本:V1.0
 8 * 日    期:2013.11.15
 9 * 联系方式:xiao13149920@foxmail.com
10 ********************************************************************************/
11 // volatile_setjmp.c
12 #include<stdio.h>
13 #include<stdlib.h>
14 #include<setjmp.h>
15 
16 static jmp_buf env;
17 
18 static void do_jump(int nvar, int rvar, int vvar)
19 {
20     printf("Inside do_jump(): nvar:%d, rvar:%d, vvar:%d
", nvar, rvar, vvar);
21     longjmp(env, 1);
22 }
23 
24 int main(int argc, char *argv[])
25 {
26     int nvar;
27     register int rvar;    // allocated in register if possible
28     volatile int vvar;    // see text
29 
30     nvar = 111;
31     rvar = 222;
32     vvar = 333;
33 
34     if (setjmp(env) == 0)
35     {
36         nvar = 777;
37         rvar = 888;
38         vvar = 999;
39         do_jump(nvar, rvar, vvar);
40     }
41     else
42     {
43         printf("After do_jump(): nvar:%d, rvar:%d, vvar:%d
", nvar, rvar, vvar);
44     }
45 
46     return 0;
47 }

1. When we compile the program with

gcc -o volatile_setjmp volatile_setjmp.c

and the output :

Inside do_jump(): nvar:777, rvar:888, vvar:999
After do_jump(): nvar:777, rvar:888, vvar:999

2.However, when we compile with optimization

gcc -O -o volatile_setjmp volatile_setjmp.

we get the following unexpected results:

Inside do_jump(): nvar:777, rvar:888, vvar:999
After do_jump(): nvar:111, rvar:222, vvar:999

We can prevent such code reorganization by declaring variables as volatile,which tells the optimizer not to optimizethem. In the preceding program output,we see that the variable vvar, which was declared volatile, was correctly handled,even when we compiled with optimization.

原文地址:https://www.cnblogs.com/xiao13149920yanyan/p/3425118.html