background image

1>告诉 compiler 不能做任何优化

 

比如要往某一地址送两指令:

int *ip =...; //

 

设备地址

*ip = 1; //

 

第一个指令

*ip = 2; //

 

第二个指令

以上程序 compiler

 

可能做优化而成:

int *ip = ...; 

*ip = 2; 

结果第一个指令丢失。如果用 volatile, compiler 就不允许做任何的优化,从而保证程序的

 

原意:

volatile int *ip = ...; 

*ip = 1; 

*ip = 2; 

即使你要 compiler 做优化,它也不会把两次付值语句间化为一。它只能做其它的优化。

2>用 volatile 定义的变量会在程序外被改变,每次都必须从内存中读取,而不能重复使

用放在 cache 或寄存器中的备份。

例如:

volatile char a;

a=0;

while(!a){

//do some things;

}

doother();

 

如果没有 volatiledoother()不会被执行

3.下面是使用 volatile 变量的几个场景:

1>中断服务程序中修改的供其它程序检测的变量需要加 volatile;

例如:

static int i=0;

int main(void)

{

     ...