3

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; 
11
  • You are aware of reasons to make a variable volatile? Commented Oct 13, 2017 at 21:03
  • @Yunnosch as far as I know it is used to tell the compiler that the variable can change at any time and therefore it must be kept in memory.But I'm not sure why anyone would use a volatile pointer Commented Oct 13, 2017 at 21:05
  • 1
    Surely your instructor expects you to either (i) refer to your lecture notes; (ii) consult your recommended reading; or (iii) think about it for yourself. If (iii), then you should at least be able to present something of your line of thought. Commented Oct 13, 2017 at 21:05
  • 1
    What in your opinion is the relevant difference between a variable and a pointer variable, which would make the use of a volatile variable sensible but not a volatile pointer variable? Commented Oct 13, 2017 at 21:19
  • 2
    To be clear: volatile int *pData; is not a volatile pointer. The 2nd is a pData as volatile pointer to volatile int Commented Oct 13, 2017 at 21:40

2 Answers 2

3

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 2nd meets the goal. volatile int * volatile pData; is a:
pData as volatile pointer to volatile int


The 1st 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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.