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

Renato Athaydes renato at athaydes.com
Sun Dec 29 21:58:40 UTC 2024


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]`
```

I thought that it would fail only if the `const` applied to the 
whole type, as in `const(char[][2])` and that the type in the 
example meant only elements are `const` but not the array itself?!

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?

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.


More information about the Digitalmars-d-learn mailing list