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.
In the constant pointers to constants, the data pointed to by the pointer is constant and cannot be changed. The pointer itself is constant and cannot change and point somewhere else.
A pointer to a const value (sometimes called a pointer to const for short) is a (non-const) pointer that points to a constant value. In the above example, ptr points to a const int . Because the data type being pointed to is const, the value being pointed to can't be changed. We can also make a pointer itself constant.
We can create a constant pointer in C, which means that the value of the pointer variable wouldn't change. We can create a pointer to a constant in C, which means that the pointer would point to a constant variable (created using const).
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.
The non-modifiability introduced by const
depends on where const
is written.
If you write
const int * ptr = &a;
(or int const * ptr = &a;
), the const
refers to the pointee, so using the pointer for writing to the destination is forbidden.
(OTOH, if wou wrote
int * const ptr = &a;
you couldn't modify ptr
.)
In your case, everything involving writing to the destination is forbidden.
This includes *ptr
and ptr[0]
(which are equivalent), but also everything involving a modification of the destination address, such as *(ptr + 2)
or ptr[2]
.
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