views:

227

answers:

3

I saw it was possible to do it but I do not understand the interest.

+3  A: 

const and volatile sound like they refer to the same idea on a variable, but they don't. A const variable can't be changed by the current code. A volatile variable may be changed by some outside entity outside the current code. It's possible to have a const volatile variable - especially something like a memory mapped register - that gets changed by the computer at a time your program can't predict, but that your code is not allowed to change directly. You can use const_cast to add or remove const or volatile ("cv-qualification") to a variable.

jwismar
+3  A: 

const and volatile are orthogonal.

const means the data is read-only.

volatile means the variable could be changing due to external reasons so the compiler needs to read the variable from memory each time it is referenced.

So removing const allows you to write what was otherwise a read-only location (the code must have some special knowledge the location is actually modifiable). You shouldn't remove volatile to write it because you could cause undefined behavior (due to 7.1.5.1/7 - If an attempt is made to refer to an object defined with a volatile-qualified type through the use of an lvalue with a non-volatile-qualified type, the program behaviour is undefined.)

R Samuel Klatchko
`const_cast` applies to both `const` and `volatile`, and while potentially removing `volatile` can cause undefined behavior, there are cases where it does not. I.e. adding memory barriers will force the compiler into not caching the variable and provides a stronger guarantee that `volatile` (not only the variable will not be cached, but it instruction will not be reordered outside of the critical section).
David Rodríguez - dribeas
+15  A: 

Here's a Dr. Dobbs article by Andrei Alexandrescu that goes into rather obscene amounts of detail about it.

tzaman
That's an exceedingly interesting article. Upvoted.
DeadMG
As with many other things Alexandrescu has written, that article is enlightening. I asked a question about that article and the abuse of the `volatile` qualifier that he proposes some time ago http://stackoverflow.com/questions/2491495/may-volatile-be-in-user-defined-types-to-help-writing-thread-safe-code
David Rodríguez - dribeas
Indeed a great article. Thanks for sharing. +1.
jweyrich
Great article, thanks!
Dpp
An oldie, but a goodie.
John Dibling
@David, i remember a discussion about that on usenet also with herb sutter involved, where alexandrescu said his point of view on volatile changed over time. I'm not sure what point of view is expressed in that article.
Johannes Schaub - litb