Reputation: 83
Compiling the following program
int main(void) {
int const c[2];
c[0] = 0;
c[1] = 1;
}
leads to error: assignment of read-only location ‘c[0]’. As I understand it, the const only applies to the location of c and so c[0] and c[1] should be mutable. Why is this error produced?
Upvotes: 2
Views: 73
Reputation: 16876
As I understand it, the const only applies to the location of c
No. You can't modify the location of the array anyway. What you probably mean is if you have a int * const
, then that indeed is a constant pointer to a modifiable int
. However, int const c[2];
is an array of 2 constant ints. As such, you have to initialize them when you declare the array:
int const c[2] = {0, 1};
In constrast:
int main(void) {
int c[2];
int* const foo = c;
foo[0] = 0;
foo[0] = 1;
//foo = malloc(sizeof(int)); doesn't work, can't modify foo, as it's constant
}
Upvotes: 8