Volatile Superstition
A rant on common misconceptions
After an argument I had recently at work about the volatile
specifier on super
scalar CPUs I decided to rant here.
Programmers memory seems to be volatile regarding the meaning of the C or C++ qualifier ‘volatile’. There are at least a dozen of articles on the internet referencing or copying in verbatim Jones Nigel and a zillion discussions on bulletin boards. Yet there is at least as much superstition among even experienced developers.
Section 6.7.2 of ISO C99 defines it simply as:
“An object that has volatile-qualified type may be modified in ways unknown to the implementation or have other unknown side effects.”
There is nothing magic about the volatile type qualifier!
It is a hint to the compiler not to make any assumptions how to optimize the ‘object’. On every access the value of the object has to be fetched.
- If a pointer is declared
volatile int* ptr
it means the content of address ptr “may be modified in ways unknown to the implementation”, for instance a hardware status register. - It does not magically make every address with relative offset to
ptr
volatile! The value*(ptr+4)
is not volatile. - It does not synchronize caches, bus access or anything alike
- It does not prevent instruction level parallelism or re-ordering by processors
End of story.