简体   繁体   English

C-使用易失性指针

[英]C - use of a volatile pointer

Why would one create a volatile pointer? 为什么要创建一个易失指针? And suppose I want a volatile pointer which points to a volatile variable, which of the following declarations would accomplish this: 并假设我想要一个volatile指针,该指针指向一个volatile变量,以下哪个声明可以实现此目的:

volatile int *pData;

or 要么

volatile int * volatile pData;

Why would one create a volatile pointer? 为什么要创建一个易失指针?

Example: To access data whose pointer is updated by a background process. 示例:访问其指针由后台进程更新的数据。

Stuff * volatile VideoFrame;
for (;;) {
  Block_Changes();
  Stuff MyCopy = *VideoFrame;
  Allow_Changes();
  Use(&MyCopy);
}

I want a volatile pointer which points to a volatile variable, which of the following declarations would accomplish this: 我想要一个易失性指针,该指针指向易失性变量,以下哪个声明可以实现此目的:

The 2 nd meets the goal. 第二个达到目标。 volatile int * volatile pData; is a: 是:
pData as volatile pointer to volatile int pData作为volatile int的volatile指针


The 1 st volatile int *pData; 第1 volatile int *pData; is a non-volatile pointer to volatile data: 是指向易失性数据的非易失性指针:
pData as pointer to volatile int pData作为指向volatile int的指针

The volitle keyword is most often used in this context. 在这种情况下,最常使用volitle关键字。 @ Eugene Sh. @尤金Sh。

One reason to use the modifier `volatile' is so the compiler does not optimize the variable out of existence. 使用修饰符“ volatile”的一个原因是,编译器不会优化变量不存在的变量。

Another reason to use the modifier 'volatile' is so when ever the code references that variable, it accesses the actual variable and not the value left in some register. 使用修饰符“ volatile”的另一个原因是,当代码引用该变量时,它访问的是实际变量,而不是某些寄存器中剩余的值。

Another reason to use the modifier 'volatile' is when the variable value can change outside the control of the current program. 使用修饰符“ volatile”的另一个原因是变量值可以在当前程序的控制范围之外更改。 For instance a hardware register or when an 'interrupt' updates the variable that your application is reading. 例如,硬件寄存器或当“中断”更新应用程序正在读取的变量时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM