The use of const with a pointer can make the pointee not modifiable by dereferencing it using the pointer in question. But why neither can I modify what the pointer is not direc
Although other answers explain the technicalities of why it doesn't work, I'd like to offer a more general reason: it's the only thing that makes sense.
The problem is that there is no general way for the compiler to decide whether p + something
is the same as p
or not, because something
can be arbitrarily complex. A rule like "Values pointed to by p
and p + 0
are unmodifiable, but other values can still be modified" cannot be checked at compile time: imagine if you wrote:
*(p + very complex expression) = ...
should your compiler be able to figure out if very complex expression
is zero? What about
int s;
scanf("%d", &s);
*(p + s) = ...
What should the compiler do in that case?
The only reasonable choice here was to make any value accessed through p
unmodifiable.