I would like to ask a question about pointer to constant declaration in C programming language. Currently I'm reading the "C in a Nutshell" book and at the section "9.3.1. Constant Pointers and Pointers to Constant Objects"
The author says:
Based on what I understand from the above mentioned information I've written the following code and I would like to ask you to check whether my understandings are correct.
For any operator that requires operands with like types, the compiler implicitly converts a pointer to a given type T into a more qualified version of the type T. If you want to convert a pointer into a pointer to a less-qualified type, you must use an explicit type conversion
If I run this code, here is the result that I obtain
int main(int argc, char *argv)
// Therefore the value of MYCONSTANT cannot be changed because it is
// declared as a constant.
int const MYCONSTANT = 1247;
// Ok, but then *iPtr1 cannot be used to change indirectly the value
// of MYCONSTANT.
int const *iPtr1 = &MYCONSTANT;
printf("The value of the constant is : %d\n", MYCONSTANT);
iPtr2 = (int *)iPtr1; // Ok, explicit type conversion (int const *) to (int *)
*iPtr2 = 8000; // Undefined running behaviour?
printf("Now, the value of the constant is : %d\n", MYCONSTANT);
Albeit, I had declared MYCONSTANT as a constant, I managed to change its value indirectly via a less qualified type pointer (int *) instead of (const int *), that is, iPtr2 instead of iPtr1.
$ gcc -Wall testscript.c -o testscript
The value of the constant is : 1247
Now, the value of the constant is : 8000
Could someone, make some clarification about this? According to the C language semantic a constant means what it means, it cannot be changed. So why I don't get any runtime error while executing this program?
Thanks in advance,