Hello everybody,
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:
...
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.
...
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.
Code:
#include <stdio.h>
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;
int *iPtr2;
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);
return 0;
}
If I run this code, here is the result that I obtain
Code:
$ gcc -Wall testscript.c -o testscript
$ ./testscript
The value of the constant is : 1247
Now, the value of the constant is : 8000
$
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.
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,
Regards,
Dariyoosh