关于关键字 volatile

关于 volatile 的使用,也是 C 语言面试的月经问题。标准答案来了:

volatile is a qualifier that is applied to a variable when it is declared. It tells the compiler that the value of the variable may change at any time-without any action being taken by the code the compiler finds nearby. The implications of this are quite serious.

翻译一下:volatile 是在声明变量时,使用的一个修饰符。这个修饰符是为了告诉编译器,这个变量虽然没有在上下文中引用,但是它的值可能随时会改变,所以,不要去对它进行优化动作!

使用场景,最多的,就是对硬件寄存器的操作;比如 IO 或者 ADC 等寄存器,他们的值会被外界的电平改变。

参考文章里介绍了下面三种使用场景:

  1. Memory-mapped peripheral registers
  2. Global variables modified by an interrupt service routine
  3. Global variables within a multi-threaded application
原文地址:https://www.cnblogs.com/pied/p/9365650.html