Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is 'volatile' parasitic in C++?

Tags:

Consider the following code:

int main()                                                                       {                                                                                  int i;                                                                           volatile int* p = &i;                                                            int *v = p;                                                                      return 0;                                                                    } 

This gives an error in g++:

$ g++ -o volatile volatile.cpp  volatile.cpp: In function ‘int main()’: volatile.cpp:6: error: invalid conversion from ‘volatile int*’ to ‘int*’ 

My intention was that I want to make p volatile. However, once I've read the value of p, I don't care if accessing v is volatile. Why is it required that v be declared volatile?

This is hypothetical code of course. In a real situation you could imagine that p points to a memory location, but is modified externally and I want v to point to the location that p pointed to at the time of v = p, even if later p is externally modified. Therefore p is volatile, but v is not.

By the way I am interested in the behaviour both when this is considered C and C++, but in C this only generates a warning, not an error.

like image 662
Steve Avatar asked Mar 19 '10 14:03

Steve


1 Answers

If you mean that the pointer should be volatile, rather than the object it points to, then declare it as

int* volatile p; 
like image 165
Mike Seymour Avatar answered Oct 19 '22 22:10

Mike Seymour