changing the value of const variable in C++ [duplicate]

This is one of the cases where a const cast is undefined, since the code was probably optimized such that w isn’t really a variable and does not really exist in the compiled code.

Try the following:

const volatile int w = 10; 
int &wr = const_cast <int &> (w); 
wr = 20; 
std::cout << w << std::endl;

Anyhow, I would not advise abusing const_cast like that.

Leave a Comment