I realize that this results in undefined behavior:
const int x = 12;
*const_cast<int*>(&x) = 13;
But does gcc do anything to prevent this from killing you, or does it just let you stand back and say "Hey you know better".
Maybe it just silently removes the const modifier in the whole program or something (I don't know I am just guessing here).
Any thoughts?
Indeed, you can cast away constness of a pointer:
5.2.11/7 Depending on the type of the object, a write operation through the pointer, lvalue or pointer to data member resulting from a const_cast that casts away a const-qualifier may produce undefined behavior
If the object referred to is a const, this is undefined behavior
7.1.6.1/4: Except that any class member declared mutable (7.1.1) can be modified, any attempt to modify a const object during its lifetime (3.8) results in undefined behavior.
And undefined behavior is... undefined:
1.3.24: behavior for which this International Standard imposes no requirements (...) Permissible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message).
So, let's imagine what could happen: may be it will work, may be it will segfault (for example, because the const data would be stored in a const memory segment), may be it will not work as expected (for example, the write is ignored), may be you can get a warning or an error at compilation. So the best is to avoid this !
Quote of the day: "C makes it easy to shoot yourself in the foot; C++ makes it harder, but when you do it blows your whole leg off" - Bjarne Stroustrup