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:
- Using a pointer with type casting:
You can cast a
constpointer 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
-
Using
mutablein classes: Ifconstis applied to a class object, fields declared withmutablecan be modified even inconstmethods. -
Via
const_castin 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.