const does not actually mean "constant." That a "constant" in C has a value defined at compile time; an example is literal 42 . The const keyword really means read only. Consider, for example:
const int r = rand();
The value of r not determined until the execution time of the program, but the const keyword means that you are not allowed to change r after it is initialized.
In your code:
const int x=1; int *ptr; ptr = &x; *ptr = 2;
assignment ptr = &x; is a violation of the restriction, which means that the corresponding compiler must complain about it; you cannot legally assign the value const int* (a pointer to const int) to a non-const int* object. If the compiler generates an executable file (which it does not need to do, it can simply reject it), then the behavior is not defined by the C standard.
For example, the generated code can actually store the value 2 in x - but then a later reference to x can give the value 1 , because the compiler knows that x can't be changed after it was initialized. And he knows that, as you said so, defining x as const . If you lie to the compiler, the consequences can be arbitrary.
Actually, the worst thing that can happen is that the program behaves the way you expect; this means that you have a mistake that is very difficult to detect. (But the diagnosis you should have received was a great clue.)
source share