On Fri, Aug 6, 2010 at 2:40 PM, lakshay <[email protected]> wrote:
>
> const int a = 100;
> const int *p = &a;
const is an indication from you, to the compiler, that no code should
be able to change the value of what's pointed to through that pointer.
Some compilers *may* put const values in read-only memory, others might not.
> int *q = (int*)p;
Here you tell the compiler to ignore the 'const' regardless of whether
it's right or wrong.
> *q = 10;
>
> cout<<*p<<*q;
>
> answer : 10 10
>
> But i am not able to understand why this is happening?
Because
1) You told the compiler not to bother you with a warning/error about
the constness of a/p when defining q
2) It would appear your compiler is placing `a` in writable memory.
Consider a situation where (2) doesn't apply (not compiled):
void foo(const int* p){
*(int*)p = 42;
}
int main(void){
int a = 10;
foo(&a);
cout << a << endl;
}
--
PJH
http://www.ipetitions.com/petition/makeitthemaximum