2
const int a = 10;
int main()
{
    int *p = &a;
    *p = 100;
    printf ("%d\n", *p);
}

The above code crashes, which is as per the expectation.

Now check the below code (Change the variable a from global to local variable).

int main()
{
    const int a = 10;

    int *p = &a;
    *p = 100;
    printf ("%d\n", *p);
}

The code prints 100 as the output. My question is that why read-write access is allowed for the local const variable?

Sumit Trehan
  • 3,985
  • 3
  • 27
  • 42
  • 1
    It isn't allowed. You are invoking undefined behaviour. – juanchopanza Sep 16 '14 at 15:53
  • It is [undefined behavior](http://stackoverflow.com/q/21372713/1708801), possible duplicate. – Shafik Yaghmour Sep 16 '14 at 15:55
  • 2
    global const may be on a memory segment which is clearly marked "read only" by the OS and protected as such. stack const is not really const at the assembly level. – UmNyobe Sep 16 '14 at 15:56
  • And you’re ignoring a warning. A compiler may refuse to compile your code. – mafso Sep 16 '14 at 15:57
  • 1
    In the question linked above, a [comment notes](http://stackoverflow.com/questions/21372713/confusion-regarding-modification-of-const-variable-using-pointers/21372732#comment32231156_21372732) ... `It's actually fairly hard for implementations to put const objects with automatic storage in read-only memory;` – Shafik Yaghmour Sep 16 '14 at 16:03
  • See also: http://stackoverflow.com/questions/4841419/what-is-the-purpose-of-const-qualifier-if-i-can-modify-it-through-a-pointer-in-c?rq=1 – Paul R Sep 16 '14 at 16:22

0 Answers0