Modifying a const
value through any mechanism (including casting away const-ness) results in "undefined behavior" (UB) which means that you cannot reason about the behavior of the program. The compiler is allowed to assume that const
values will never change. Based on that assumption, the compiler might:
- Store
const
values in read-only memory pages; attempting assignment through the pointer would then cause an access violation.
- Inline the
const
value wherever it is used. Because you take a pointer, the compiler will likely also emit some kind of storage for the value (on the stack most likely) so that it has a memory location that can be pointed to, but modifying this value will not cause the inlined values to change.
- Something else, possibly including both of the above.
Which one it does can depend on the optimization level selected.
A program that assigns to a const
value is effectively "nonsense" and has no meaningful interpretation.
Note that this is UB in both C and C++. You just need to twist the C++ compiler's arm a bit more to get the code to compile (int *ptr = const_cast<int *>(&var);
). The C standard permits implicit discarding of a const
qualifier in some contexts; the C++ standard is a lot more strict about this.
Most C compilers will emit a warning on int *ptr = &var;
regarding discarding of the const
qualifier. I would strongly recommend compiling with all warnings enabled and converted to errors (-Wall -Werror
on gcc). That would cause the C compiler to also refuse to compile this code.
Note that casting const
away from a pointer (or reference) and assigning to the target is not UB when the value was not declared const
:
// non-const value
int x = 10;
// take a pointer to x and store it in a pointer-to-const
const int *y = &x;
// cast away the const-ness of the pointer target
int *z = const_cast<int *>(y);
// this is fine; z points at x which is not const
*z = 5;
However, if you find yourself needing const_cast
then most likely you are either (1) doing some crazy template metaprogramming, or (2) approaching the problem wrong.