被volatile修饰的变量,每次都去内存中取值,避免了编译器优化,不从寄存器中取。但是不能用一个非volatile的变量去引用volatile变量
错误代码
#include <stdio.h>
void func(void) {
static volatile int **ipp;
static int *ip;
static volatile int i = 0;
printf("i = %d.\n", i);
ipp = &ip; /* May produce a warning diagnostic */
ipp = (int**) &ip; /* Constraint violation; may produce a warning diagnostic */
*ipp = &i; /* Valid */
if (*ip != 0) { /* Valid */
/* ... */
}
}
正确代码
#include <stdio.h>
void func(void) {
static volatile int **ipp;
static volatile int *ip;
static volatile int i = 0;
printf("i = %d.\n", i);
ipp = &ip;
*ipp = &i;
if (*ip != 0) {
/* ... */
}
}