I saw it was possible to do it but I do not understand the interest.
-
Are you asking about casting from a `const volatile` to a `volatile` or something else? – R Samuel Klatchko Jun 12 '10 at 22:48
-
1Learned something new about the volatile casting being done with const_cast, and moved my accidentally off-topic (but related) answer to valid scenarios for const_casting here: http://hostilefork.com/2010/06/12/when-should-one-use-const_cast-anyway/ – HostileFork says dont trust SE Jun 13 '10 at 04:39
2 Answers
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.

- 12,164
- 3
- 32
- 44
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.
)

- 74,869
- 16
- 134
- 187
-
3`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 Jun 12 '10 at 23:49