The reason you could modify the value is because you did a pointer typecast that stripped off the const
ness:
int *p = (int *)&a;
This typecasts a const int*
(namely &a
) to an int *
, allowing you to freely modify the variable. Normally the compiler would warn you about this, but the explicit typecast suppressed the warning.
The main rationale behind const
at all is to prevent you from accidentally modifying something that you promised not to. It's not sacrosanct, as you've seen, and you can cast away const
ness with impunity, much in the same way that you can do other unsafe things like converting pointers to integers or vice-versa. The idea is that you should try your best not to mess with const
, and the compiler will warn you if you do. Of course, adding in a cast tells the compiler "I know what I'm doing," and so in your case the above doesn't generate any sort of warnings.