Following example added confusion in my understanding. I'm unable to understand how is it possible to modify the const variable local. Please help me to understand the same.
/* Compile code without optimization option */
// volatile.c
#include <stdio.h>
int main(void)
{
const int local = 10;
int *ptr = (int*) &local;
printf("Initial value of local : %d \n", local);
*ptr = 100;
printf("Modified value of local: %d \n", local);
return 0;
}
$ gcc volatile.c -o volatile –save-temps
$ ./volatile
Initial value of local : 10
Modified value of local: 100
This is simply undefined behavior if we look at the C99 draft standard section
6.7.3
Type qualifiers paragraph 4 it says:So you can not have any expectations on the results and you should not be doing this.
If we look at paragraph 2 it says:
and footnote
114
says:In general the implementation does not have to make const variables read-only but it may but as R.. points out placing an automatic variable in read-only memory would be hard.