int main()
{
const int ia = 10;
int *pia = const_cast<int*>(&ia);
*pia = 5;
std::cout << &ia << "\t" << pia <<endl;
std::cout << ia << "\t" << *pia <<endl;
return 0;
}
The output is:
0x28fef4 0x28fef4
10 5
*pia
and ia
have the same address, but they have different values. My purpose is to use const_cast
to modify a constant value, but as the result shows that it does not work.
Does anyone know why?
Constants are block-scoped, much like variables declared using the let keyword. The value of a constant can't be changed through reassignment (i.e. by using the assignment operator), and it can't be redeclared (i.e. through a variable declaration).
In C or C++, we can use the constant variables. The constant variable values cannot be changed after its initialization.
const_cast is one of the type casting operators. It is used to change the constant value of any object or we can say it is used to remove the constant nature of any object. const_cast can be used in programs that have any object with some constant value which need to be changed occasionally at some point.
Overview. A constant is a value that cannot be altered by the program during normal execution, i.e., the value is constant.
The reason why you see 10
printed for ia
is most likely the compiler optimization: it sees a const
object, decides that it's not going to change, and replaces the last printout with this:
cout<< 10 <<" "<<*ppa<<endl;
In other words, the generated code has the value of the const
"baked into" the binary.
Casting away the const-ness of an object that has originally been declared as const
and writing to that object is undefined behavior:
$5.2.11/7 - Note: 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-qualifier68) may produce undefined behavior (7.1.5.1).
Depending on the platform, const
objects may be placed in a protected region of memory, to which you cannot write. Working around the const
-ness in the type system may help your program compile, but you may see random results or even crashes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With