September 20, 2015
I went through these two links and found that this behaviour is undefined , but the only issue which I have is that in one sense we say that since local variables live on stack , hence they cannot be located on read only memory region but if this is so then if I try to alter the value of the constant directly through assignment then why does it show error if it is not located in the read only memory region :

#include<stdio.h>
int main()
{
const int a=12;
int *ptr ;
ptr=&a;
*ptr=8; // no error
a=45; // error
printf("\n %d", a);
return 0;
}


1. http://stackoverflow.com/questions/945640/why-can-i-change-a-local-const-variable-through-pointer-casts-but-not-a-global-o


2. http://stackoverflow.com/questions/3801557/can-we-change-the-value-of-a-constant-through-pointers
September 20, 2015
On Sunday, 20 September 2015 at 00:09:52 UTC, RADHA GOGIA wrote:
> I went through these two links and found that this behaviour is undefined , but the only issue which I have is that in one sense we say that since local variables live on stack , hence they cannot be located on read only memory region but if this is so then if I try to alter the value of the constant directly through assignment then why does it show error if it is not located in the read only memory region :


const in C (and D) isn't necessarily related to read-only memory on the hardware level. It is a feature of the type system - because the VARIABLE is marked const, the compiler will complain if you try to write to it.


> const int a=12;
> int *ptr ;
> ptr=&a;
> *ptr=8; // no error

BTW, that is allowed in C, but would be a compile error in D - D's type system propagates the const to pointers too.