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.
If you mean that the pointer should be volatile, rather than the object it points to, then declare it as
int* volatile p;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With