Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

constants

I am trying to change the value of a variable which is defined as int const as below.

const int w = 10;
int* wp = const_cast <int*> (&w);
*wp = 20;

The value of w didn't change and was 10 even after the assignment, though it shows as if both w and wp are pointing to the same memory location. But I am able to the change the value of w, if defined as below while declaring

int i = 10;
const int w = i;

If I change the declaration of i to make it const like in

const int i = 10;

The value of w doesn't change.

In the first case, how come the value of w didn't change, even though w and wp point to the same memory location [ that was my impression I get when I print their addresses ]

What difference it's to the compiler that it treats both the cases differently?

Is there a way to make sure that w doesn't lose constness, irrespective of the way it is defined?

like image 894
Narendra N Avatar asked Jan 05 '10 13:01

Narendra N


1 Answers

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.

like image 88
rmn Avatar answered Oct 10 '22 10:10

rmn