第1题: 考查对volatile关键字的认识
#include
static jmp_buf buf;
main() {
volatile int b;
b =3;
if(setjmp(buf)!=0) {
printf("%d ", b);
exit(0);
}
b=5;
longjmp(buf , 1);
}
请问,这段程序的输出是
(a) 3
(b) 5
(c) 0
(d) 以上均不是
答案是b!
volatile字面意思是易于挥发的。这个关键字来描述一个变量时,意味着 给该变量赋值(写入)之后,马上再读取,写入的值与读取的值可能不一样,所以说它"容易挥发"的。
这是因为这个变量可能一个寄存器,直接与外部设备相连,你写入之后,该寄存器也有可能被外部设备的写操作所改变;或者,该变量被一个中断程序,或另一个进程
改变了.
volatile 不会被编译器优化影响,在longjump 后,它的值 是后面假定的变量值,b最后的值是5,所以5被打印出来.
setjmp : 设置非局部跳转 /* setjmp.h*/
Stores context information such as register values so that the lomgjmp function can return control to the statement following the one calling setjmp.Returns 0 when it is initially called.
Lonjjmp: 执行一个非局部跳转 /* setjmp.h*/
Transfers control to the statement where the call to setjmp (which initialized buf) was made. Execution continues at this point as if longjmp cannot return the value 0.A nonvolatile automatic variable might be changed by a call to longjmp.When you use setjmp and longjmp, the only automatic variables guaranteed to remain valid are those declared volatile.
Note: Test program without volatile qualifier (result may very)
更详细介绍,请参阅 C语言的setjmp和longjmp