Sobes.tech
Junior — Middle

How can the value of a variable declared as const be changed in C++?

sobes.tech AI

Answer from AI

In C++, a variable declared with the keyword const cannot be modified directly. However, there are ways to bypass this restriction, although they are not recommended for regular code, as they violate constancy and can lead to undefined behavior.

One way is to use const_cast to remove constness:

const int x = 10;
int* p = const_cast<int*>(&x);
*p = 20; // changes the value of x (unsafe)

It is important to understand that if a variable is initially declared as const, changing its value through const_cast leads to undefined behavior.

Another way is to change the value through a pointer to memory if the variable was not originally declared as const, and constness was only imposed through a reference or pointer.

Overall, it is not advisable to change const variables, as it violates the concept of immutability and can lead to errors.