problem with casting a Const varibale..?

Hi ,

I have a doubt in "const " variable de-referencing.

#include<iostream>
using namespace std;
int main() {
const int i = 0;
j = const_cast<int*>(&i);
*j=2; // De- referencing the Const variable
cout << "i=" << i << endl;
cout << "Address of i " <<&i << endl;
cout << " Address Pointed by j" << j << endl;
cout << " Value of Address pointed J" << *j << endl;
}

In the above code. Value of i is 0 and *j is 2. My question is where this '2' will be stored ?
A const int may not be given any storage, which means you won't be able to obtain its address (as it doesn't have one).

It works this way to provide an alternative to using #define .

Your example doesn't declare j, I assume it's int*.
Thanks
Hi .. I still have some doubt. I have added few printouts in my code as below.

#include<iostream>
using namespace std;
int main() {
const int i = 0;
int *j;
j = const_cast<int*>(&i);
*j=2; // De- referencing the Const variable
cout << "i = " << i << endl;
cout << "Address of i = " <<&i << endl;
cout << "*&i =" << *&i << endl;
cout << "Address Pointed by j = " << j << endl;
cout << "Value of Address pointed by J = " << *j << endl;
}

Here is the output


i = 0
Address of i = 0x7fff3d83e75c
*&i =0
Address Pointed by j = 0x7fff3d83e75c
Value of Address pointed by J = 2

My question is , If compiler is forced to allocate address due to casting. Then *&i and *p should have same value right. How can a address have two values ?
Topic archived. No new replies allowed.