I'm learning C++ from past few days and when learning about the const qualifier
tried the below:
const int m = 10;
int main()
{
int* lptr;
int* gptr;
const int i = 20;
lptr = (int *)&i;
*lptr = 40; //line 1
cout<<i<<endl;
cout<<*lptr<<endl;
*gptr = (int*)&m;
*gptr = 50; //line 2
cout<<m<<endl;
cout<<*gptr<<endl;
}
Here, since I'm casting the const int*
to int*
explicitly, the code compilation is perfectly alright. In line 1
, I'm surprised to see that there is no run time error(access violation). But in line 2
there is a run time error saying write access violation
(which is expected as const variables are placed in ro memory). But here why the local const variable is allowed to be modified through lptr
. Is there nothing like a read only memory on the stack also? (and if it doesn't then how safe is using const local variables as it can be modified with a pointer)
*I'm using MSVC++ 14.0 *
I know that const variables are not meant to be modified, but since I'm leaning from basics I'm exploring the different ways