简体   繁体   中英

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 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


The 1 st volatile int *pData; is a non-volatile pointer to volatile data:
pData as pointer to volatile int

The volitle keyword is most often used in this context. @ Eugene Sh.

One reason to use the modifier `volatile' is so the compiler does not optimize the variable out of existence.

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.

Another reason to use the modifier 'volatile' is when the variable value can change outside the control of the current program. For instance a hardware register or when an 'interrupt' updates the variable that your application is reading.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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