Oh so it is the same as const. Well I guess I learnt something today.
Oh so it is the same as const. Well I guess I learnt something today.
My homepage
Advice: Take only as directed - If symptoms persist, please see your debugger
Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"
But in this case, that's exactly what we want, isn't it? We have a pointer-to-volatile, and we are dereferencing the pointer; therefore we are accessing the volatile object that is being pointed to. And accessing a volatile object is exactly the thing that can't be omitted.
The second article in post #3 has a section:
>> 3. Global variables accessed by multiple tasks within a multi-threaded application
which is completely false and incorrect - for reasons grumpy has already mentioned (and the first article).
volatile does not provide memory visibility and ordering guarantees (at the hardware level) which only synchronization primitives from your threading library can provide. Thankfully, this is now in the C++0x standard, including a threading library (yay!).
>> I have always understood volatile as meaning the variable can be changed outside of program flow
I've never liked that explanation. In my mind, it only implies what really should happen instead of just stating is explicitly. That is, 'all volatile accesses must be emitted by the compiler as accesses that hit the address bus'.
It doesn't have to be the case that the "variable can change outside of the program". Writing to a memory location may turn on an LED (or some other external side-effect). By making that write a volatile access, the compiler must emit a write access on the address bus, even though it may not see any in-program side-effects for doing so (compiler doesn't know about the LED).
Another (contrived) example: Three reads from memory will turn on an LED (or set a centrifuge to its maximum RPM):
Most self-respecting compilers would optimize these down to 1 or 0 memory accesses. But if the accesses are volatile, then all 3 accesses must be emitted.Code:dummy = *ptr; dummy = *ptr; dummy = *ptr;
Another (contrived) example: Two reads and a write will turn on an LED:
As volatile accesses, this must be emitted as 2 reads followed by a write. The compiler is not allowed to change the ordering of volatile accesses. However, the compiler is allowed to re-order all non-volatile accesses.Code:a = *ptr; b = *ptr; *ptr = 1;
gg