The variable i
is declared const but still I am able to change the value with a pointer to the memory location to it. How is it possible?
int main()
{
const int i = 11;
int *ip = &i;
*ip=100;
printf("%d\n",*ip);
printf("%d\n",i);
}
When I compile, I get this warning :
test.c: In function ‘main’:
test.c:11: warning: initialization discards qualifiers from pointer target type
Output is this
100
100
const
is a compile-time feature.
It doesn't prevent you from shooting yourself in the foot; that's what the warning is for.
The const
is not a request to the compiler to make it impossible to change that variable. Rather, it is a promise to the compiler that you won't. If you break your promise, your program is allowed to do anything at all, including crash.
For example, if I compile your example code using gcc with the -O2
optimisation level, the output is:
100
11
The compiler is allowed to place a const
qualified variable in read-only memory, but it doesn't have to (apart from anything else, some environments don't implement any such thing). In particular, it is almost always impractical for automatic ("local") variables to be placed in read-only memory.
If you change the declaration of of i
to:
static const int i = 11;
then you may well find that the program now crashes at runtime.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With