Is this undefined behavior with const_cast? [duplicate]
What is happening here?
const int a = 0;
const int *pa = &a;
int *p = const_cast<int*>(pa);
*p = 1; // undefined behavior ??
cout << a << *p; // ??
My compiler outputs 0 and 1, but address of 'a' and value of 'p' is the same, so I'm confused how is this possible.
Solution 1:
Quote from cppreference:
Even though const_cast may remove constness or volatility from any pointer or reference, using the resulting pointer or reference to write to an object that was declared const or to access an object that was declared volatile invokes undefined behavior.
So yes, modifying constant variables is undefined behavior. The output you see is caused by the fact that you tell the compiler that the value of a
will never change, so it can just put a literal 0 instead of the variable a
in the cout
line.
Solution 2:
§7.1.6.1 [dcl.type.cv]/p4:
Except that any class member declared
mutable
(7.1.1) can be modified, any attempt to modify aconst
object during its lifetime (3.8) results in undefined behavior.
Solution 3:
Attempting to write on a const value is undefined behavior, for example to allow the compiler to allocate const
values into read only memory (usually in code segment) or inline their value into expressions at compile time, which is what happens in your case.