There is a reason that "mystr"
decays to a pointer of type const char*
instead of char*
. You are not allowed to modify a string literal. The type is ensuring that you won't be able to try it and the the compiler will tell you if you try, but you chose to tell the compiler that you don't care about the warning by casting const
away. You shouldn't expect that to be allowed. const_cast
is always dangerous and should only be used if you are 100% sure that the object that the pointer references isn't actually a const
object. It is very rarely necessary.
By the way, modifying a string literal will not cause a C++ exception, it will cause undefined behavior.
myStr2[1] = 'a';
is modifying elements of the array named myStr2
, not of the string literal. The array is not declared with const
, so modifying it is allowed.
If you wrote
const char myStr2[6] = "myStr";
char* myStr = const_cast<char*>(myStr2);
myStr[1] = 'a';
you would have the exact same problem as with the string literal. String literals are also const char
arrays.