我知道volatile修饰符已经讨论过很多了。请不要对我大喊大叫。我知道为什么要使用它,但我正试图在使用Visual Studio 2008和2010的多线程C程序中正确使用它。它在Windows 10上遇到了一些问题。在一个简单的声明中,我把修饰符放在哪里有关系吗?例如,这两个都成功构建了,但我想知道对编译器的意义是否有什么不同:
// difference if any between these two?
volatile char _initialized = 0;
char volatile _initialized = 0;
那么一个更复杂的声明呢?给定这种结构:
typedef struct _KEY_HANDLE
{
ULONG handle;
void *ptr;
} KEY_HANDLE;
...
// difference if any between these three
volatile KEY_HANDLE * key_handles = NULL;
KEY_HANDLE volatile * key_handles = NULL;
KEY_HANDLE * volatile key_handles = NULL;
...
key_handles = (PVOID) malloc(bufsz);
...
谢谢。
https://barrgroup.com/Embedded-Systems/How-To/C-Volatile-Keyword
根据这个链接,前两个字符都是相同的。
类似地,两个KEY_HANDLE指针是指向易失性KEY_HANDLE的指针,而第三个指针是指向非易失性HEY_HANDLE的易失性指针。
volatile KEY_HANDLE * key_handles = NULL; //pointer to a volatile KEY_HANDLE
KEY_HANDLE volatile * key_handles = NULL; //pointer to a volatile KEY_HANDLE
KEY_HANDLE * volatile key_handles = NULL; //volatile pointer to a non-volatile KEY_HANDLE
对于基本类型:
volatile unit32_t *number; //The number pointed at is volatile
uint32_t *volatile number; //The pointer is volatile
volatile uint32_t number; //The number is volatile
对于结构:
volatile struct_t *struct_p; //The members of the struct pointed at are volatile
struct_t *volatile struct_p; //The pointer is volatile
volatile struct_t struct_o; //The members of the struct are volatile
这些当然可以组合:
volatile uint32_t *volatile number; //Both the pointer and the number are volatile
希望现在您能看到volatile修饰符根据位置所做的操作模式。
我没有使用过像这样的挥发性物质:
uint32_t volatile number; //I assume it will mean that the number is volatile
uint32_t volatile *number; //I assume it will mean that the number is volatile
经验法则是,如果volatile修饰符在*(指针(后面,它会修改指针,而不是所指向的变量。
就volatile it本身的含义而言,它基本上意味着编译器不能假设变量中可能存储的数据,因此不能优化对变量的任何操作。