Array literals REALLY should be immutable

Don nospam at nospam.com
Fri Nov 13 01:57:52 PST 2009


Walter Bright wrote:
> Don wrote:
>> Especially when it's creating an inconsistency with string literals.
> 
> 
> The inconsistency bothers me, too, but then there's the case:
> 
>    int x;
>    ...
>    [1, 2, x]
> 
> That can't be made immutable. Shouldn't it work? There's no analog for 
> that for string literals, so the inconsistency isn't quite complete.

I don't think it should work.

[1, 2, x] is totally different from, and a far more complicated beast 
than [1, 2, 3]. [1, 2, x] either allocates memory and performs some form 
of memory copy, or else it pokes the 'x' value into a half-initialised 
static array, exposing the code to a possible race condition. The latter 
is just a standard lookup table, that results in no code generation.
I don't see why these two very different operations should share the 
same syntax -- they don't actually have much in common.

It'd be nice to able to say that "abcd" and ['a', 'b', 'c', 'd'] are 
completely identical.

C++ got away with using the same syntax for these two totally different 
things, because (1) it doesn't have any kind of constant folding/CTFE, 
so it can look at the array entries and determine whether it's immutable 
or not; and (2) it ignores multi-core issues.

The fact that the language doesn't have any syntax for an immutable 
array literal is really a problem. Some people are getting around it by 
using a CTFE function to convert all the values to a string literal, 
then casting that string literal to (say) an array of ints. That's 
currently the only way to make the compiler generate decent code, and 
it's quite dreadful.

BTW, I'm pretty sure that making array literals immutable would simplify 
the compiler. EG, I've noticed that mutable array literals cause many 
problems for the interpreter.



More information about the Digitalmars-d mailing list