Sobes.tech
Junior — Middle

How can the value of a variable declared with the const keyword be changed?

sobes.tech AI

Answer from AI

In C/C++, a variable declared with the keyword const is ideally not modifiable after initialization. However, there are ways to bypass this restriction, although they are not recommended and can lead to undefined behavior:

  1. Using a pointer with type casting: You can cast a const pointer to a non-const pointer and modify the value through it.
const int x = 10;
int* p = (int*)&x;
*p = 20;  // Changing the value of x
  1. Using mutable in classes: If const is applied to a class object, fields declared with mutable can be modified even in const methods.

  2. Via const_cast in C++:

const int x = 10;
int& y = const_cast<int&>(x);
y = 20;

But remember, changing a const variable that is truly declared as a constant (for example, in read-only memory) will lead to undefined behavior.

Therefore, directly changing a const variable is not allowed, and workarounds should be used with great caution and only if you fully understand the consequences.