int i;
int j;
int * const ptr1 = &i;
The compiler will stop you changing ptr1
.
const int * ptr2 = &i;
The compiler will stop you changing *ptr2
.
ptr1 = &j; // error
*ptr1 = 7; // ok
ptr2 = &j; // ok
*ptr2 = 7; // error
Note that you can still change *ptr2
, just not by literally typing *ptr2
:
i = 4;
printf("before: %d\n", *ptr2); // prints 4
i = 5;
printf("after: %d\n", *ptr2); // prints 5
*ptr2 = 6; // still an error
You can also have a pointer with both features:
const int * const ptr3 = &i;
ptr3 = &j; // error
*ptr3 = 7; // error