Why I can't modify a const(char[])[N]?

Ali Çehreli acehreli at yahoo.com
Mon Dec 30 03:44:09 UTC 2024


On 12/29/24 1:58 PM, Renato Athaydes wrote:
 > I must be misunderstanding how const types work.
 >
 > I expected this to be accepted by the compiler:
 >
 > ```
 > void foo(const(char[]) c) {
 >    const(char[])[2] d;
 >    d[0] = c;
 > }
 > ```
 >
 > But it isn't:
 >
 > ```
 > Error: cannot modify `const` expression `d[0]`
 > ```

It's the same issue with the following code:

     const(char[]) a;
     a = c;

The only difference in your example is the fact that my variable 'a' 
happens to be array element for you. They are both const(char[]) and 
cannot be modified.

 > I thought that it would fail only if the `const` applied to the whole
 > type,

That would be true but it's "turtles all the way down": everthing that 
is accessed through a 'const' expression would be 'const'.

 > as in `const(char[][2])` and that the type in the example meant
 > only elements are `const` but not the array itself?!

That's true. But the problem you are having is that you are trying to 
change an element that is 'const'.

 > However, this kind of thing works with slices:
 >
 > ```
 > void foo(const(char[]) c) {
 >    const(char[])[] d;
 >    d ~= c;
 > }
 > ```
 >
 > Why is this ok, but not the previous one?

Because now you are not changing any element; you are changing the 
array, which is not const. The following will still fail with your new 
example:

   d[0] = c;

 > If I use `const(char[][])` instead, then it does fail as I had
 > expected... so I can't see where is the hole in my understanding.

Ali



More information about the Digitalmars-d-learn mailing list