They are correct, it is undefined behaviour. You're not allowed to modify the value of a const
variable, which is the danger of casting away the const
ness of something: you better know it's not really const
.
The compiler, seeing that maxint
is const
and should never be modified, doesn't even have to give it an address. It can just replace all the uses of maxint
with 100 if it sees fit. Also it might just put the constant in to a portion of memory that is read-only, as Matteo Italia points out, which is probably what's happening for you. That's why modifying it produces undefined behaviour.
The only way you can safely cast away the const
ness of a variable is if the variable is not actually const
, but the const
qualifier was added to a non-const
variable, like this:
int f(const int& x) {
int& nonconst = const_cast<int&>(x);
++nonconst;
}
int blah = 523;
f(blah); // this is safe
const int constblah = 123;
f(constblah); // this is undefined behaviour
Think about this example, which compiles perfectly:
int f(const int& x) {
int& nonconst = const_cast<int&>(x);
++nonconst;
}
int main() {
f(4); // incrementing a number literal???
}
You can see how using const_cast
is pretty dangerous because there's no way to actually tell whether a variable is originally const
or not. You should avoid using const_cast
when possible (with functions, by just not accepting const
parameters).