int main()
{
const int maxint=100;//The program will crash if this line is put outside the main
int &msg=const_cast<int&>(maxint);
msg=200;
cout<<"max:"<<msg<<endl;
return 0;
}
The function will run ok if the ‘const int maxint=100;’ definition is put inside the main function but crash and popup a error message said “Access Violation” if put outside.
Someone says it’s some kind of ‘undefined behavior’, and i want to know the exact answer and how i can use the const cast safely?
They are correct, it is undefined behaviour. You’re not allowed to modify the value of a
constvariable, which is the danger of casting away theconstness of something: you better know it’s not reallyconst.The compiler, seeing that
maxintisconstand should never be modified, doesn’t even have to give it an address. It can just replace all the uses ofmaxintwith 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
constness of a variable is if the variable is not actuallyconst, but theconstqualifier was added to a non-constvariable, like this:Think about this example, which compiles perfectly:
You can see how using
const_castis pretty dangerous because there’s no way to actually tell whether a variable is originallyconstor not. You should avoid usingconst_castwhen possible (with functions, by just not acceptingconstparameters).