Let
int i = 1;
const int *p = &i;
Why can I change i
but not *p
? Or rather, what happens behind the scenes that allows me to write i = 5
but not *p = 5
?
Let
int i = 1;
const int *p = &i;
Why can I change i
but not *p
? Or rather, what happens behind the scenes that allows me to write i = 5
but not *p = 5
?
By declaring p
as a pointer to const int
you are making promise to compiler to not to modify the object pointed by p
using dereference through p
. It's on you if you are keeping your promise or break it by changing the object pointed by p
by other means.
There is nothing behind the scene. Everything is on the complier side.
i
denotes an identifier that references a memory chunk able to store an int
value. Through that i
you can either read or write.
p
denotes a pointer to a const int
. That only means that through p
you are not able to write the pointed int
, only read. p
is a view to an int
which let not you modify it. That's all. And this is a property ensured at compilation.
Now think of definition/declaration as typed access to memory tainted with access rights.
First of all it is not const pointer
only pointer to const object
.
In the fact you just promise the compiler that you do not want object referenced by the pointer to be changed by the dereference of this pointer. Compiler will trace (but only compiler) attempts to assign new value to the object in the source code. There is no runtime check and you can of course (if the object is not in the read only memory) change it by tricking the compiler in the source code.
You told the compiler "I am not going to try assigning to *p
" (that is really all there is to const
), but that says nothing about i
.
#include <stdio.h>
void main(void) {
int i = 1;
const int *p = &i;
printf("i=%d\np*=%d\n", i, p);
i = 5;
printf("i=%d\np*=%d\n", i, p);
*p = 10;
printf("i=%d\np*=%d\n", i, p);
}
GCC will complain about assignment of read-only location '*p'
, but i=5
is fine, since i
is not const
. Remove the const
from *p
, or remove the assignment *p=10
, and everything is good.
If the reference to i
were to somehow disappear, then that memory space would effectively become read-only from the programmer's perspective: the compiler won't let me write to *p
, and that is the only handle I have left for that piece of memory.