Constant variables also allows the compiler certain optimizations, one of these is that the compiler can keep the value in the registers and not reload it. This improves performance but will not work with variables that changes since these need to be reread. Some compilers even optimize constants by not allocating a variable, but simply replacing the value inline. If you change the variable a to int
instead of const int
it will work, as it can be read in the documentation about the const_cast
operator from IBM:
If you cast away the constness of an
object that has been explicitly
declared as const, and attempt to
modify it, the results are undefined.
You can find more information about the problem you are having and why it doesn't work here:
On a side note it can be noted that if you find yourself in need of using the const_cast
there is a good chance that you should reconsider your design instead.