I think chqrlie is right when he says that the error message "assignment of read-only location '*foo'" is misleading. Actually, const int *foo
(i.e. a pointer defined as pointing to a const int
) does not mean that the memory addressed by the pointer is or becomes immutable per se; it just means that the memory addressed by the pointer must not be changed through this pointer; it might, however, be changed in other ways. You could define, for example a second pointer int *foo2 = &b
through which you may change the value addressed by foo2
.
So you may think of the pointer as being a separate view to a value at a particular memory address, and one may declare the view as read-only or not. This does, however, not effect whether the value at the particular memory address per se is immutable or not:
int main()
{
int b=15; // b is mutable
const int* foo=&b; // *foo is immutable; b remains mutable
int *foo2=&b; // *foo2 is mutable
b=20; // allowed, since b is mutable
*foo=20; // not allowed, since "*foo" is immutable, even if the value to which it points (i.e. b) would be mutable
*foo2=20; // allowed, since "*foo2" is mutable
return 0;
}
Though not asked, the other way round, you actually may define a value as being immutable, and this value must then not be altered in any way; if you somehow manipulated the value by writing to its memory address, the behaviour is undefined:
const int c = 15; // c is immutable
int* bar = &c; // warning: discards const qualifier
printf("%d\n", c);
*bar = 20; // undefined behaviour from here on; modifying a const value is not allowed.
printf("%d\n", c); // undefined behaviour; good chance that it still prints 15, because a compiler might have relied on the fact that c is 15 and immutable
printf("%d\n", *bar); // undefined behaviour; probably printing 20?
Hope it helps.