Jan 18, 2009

Consider the following c++ program #include using namespace std; int main() { const int a=10; int* b=(int*)&a; *b=20; cout<<

Consider the following c++ program
#include
using namespace std;
int main()
{
const int a=10;
int* b=(int*)&a;
*b=20;
cout<<&a<<'\n'<<&b<<'\n';
cout<<a<<'\n'<<*(&a)<<'\n'<<*b;
return 0;
}

This is what I got as output
0x22ff54
0x22ff54
10
10
20
Can anyone explain how I got different values as output when it is the same memory location I'm accessing.
BTW I was trying to override the constness of 'a'.
&a and b gave the same address as output but it gave different values for a and *b. I find it strange ( I'm perhaps missing something).

A is declared const therefore the compiler is allowed to treat it as constant. It optimized the print of a known constant at compile time. In the case of b you find it actually set the value. Putting your prints in a function may be enough to fool it into a= 20 b =20;
If you are making a class and need nonconst elements in a const instance use mutable. const_cast is the preferred way to make constness go away in C++. Though it still wouldn't save you in this case because something that is declared constant is assumed to be constant and optimized accordingly. Const casting is just there to provide wiggle room to users of libraries that are not const correct.

No comments:

Post a Comment