C Programming – Using const with Pointers

c++constantspointers

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 directly pointing to?

For example:

int a = 3;
const int* ptr = &a;
*ptr = 5;

will not compile. But why does

*(ptr + 2) = 5;

also not compile? I'm not changing what the pointer is pointing to.
So do we have to say that using const with a pointer in such a way not only makes not modifiable what the pointer is pointing to (by dereferencing the pointer) but also anything else, to which the adress we get using the pointer?

I know that in the example I'm trying to access not allocated memory, but this is just for the sake of discussion.

Best Answer

ptr +2 simply has the same type as ptr namely is a pointer to a const object.

Pointer arithmetic supposes that the object that is pointed to is an array of all the same base type. This type includes the const qualification.