2

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?

3
  • 5
    "int const array cannot be written to" Indeed, that is the purpose of const. Commented Jan 13, 2020 at 14:25
  • Oh btw, ` int const c[2];` with semicolon and no initializer list is kind of a language bug. The C language allows you to declare a constant without initializing it. C++ does not. Commented Jan 13, 2020 at 14:29
  • To get the behavior you describe in the question you could write int (*const c)[10]; *c[1] = 5; Commented Jan 13, 2020 at 14:29

1 Answer 1

8

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
}
Sign up to request clarification or add additional context in comments.

6 Comments

It doesn't matter if you write "int const" or "const int", does it? I have never seen "int const" written before. (I am aware that this was taken over from the question.)
the order does not matter in this case.
@AndreasWenzel const int and int const are equivalent - the latter is weird style. const int* and int * const however, mean different things.
(We can even write const const const int x. Because.... C...)
@Blaze All that matters is if it's on the left or right side of the *. Your "left of it" rule doesn't hold. Consider auto const const int const signed const x = 0;
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.