Behaviour of const_cast??

#include "stdafx.h"


int test(const int &i)

{

int *ptr = const_cast<int*>(&i);

*ptr = 5;

printf("\n in function %d", i);

return 0;

}

int _tmain(int argc, _TCHAR* argv[])

{

int const j=100;

const int *ptr = reinterpret_cast<const int *> (&j);

printf ("\nj = %d",j);

test(j);

printf ("\nafter function call j = %d",j);

int k=100;

printf ("\nj = %d",k);

test( k );

printf ("\nj = %d",k);


getchar();
return 0;

}

why I am not getting changed value of j from function test() in main function. Really strange behavior to me as it modifying same memory location
You declared j as const, so it's perfectly reasonable for the compiler to have put that number in a location that cannot be written to, so when you discard the const qualifier and try to edit it the operation fails. You are invoking undefined behavior by trying to do what you are doing.
Topic archived. No new replies allowed.