-3

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

infinite loop
  • 1,309
  • 9
  • 19

1 Answers1

1

Just because you can cast away const and then write to a const variable through a pointer to non-const does not make it legal. In fact it is undefined behaviour and your program is ill formed and has no meaning. The compiler is free to generate whatever code it feels like in that case.

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70