How to initialize static arrays with variable data

Steven Schveighoffer schveiguy at yahoo.com
Fri Feb 19 10:18:02 PST 2010


On Fri, 19 Feb 2010 12:53:56 -0500, Denis Koroskin <2korden at gmail.com>  
wrote:

> On Fri, 19 Feb 2010 20:28:20 +0300, Steven Schveighoffer
> <schveiguy at yahoo.com> wrote:
>
>> On Fri, 19 Feb 2010 12:15:20 -0500, bearophile  
>> <bearophileHUGS at lycos.com> wrote:
>>
>>> Steven Schveighoffer:
>>>
>>>> It would be nice to allow this:
>>>> int[3] x = [a, b, c];
>>>
>>> This is allowed now.
>>
>> Yes, but 1) it allocates the literal on the heap and then throws it  
>> away, and 2) it would not be allowed if array literals are only allowed  
>> to be immutable.  I'm speaking from the context assuming that array  
>> literals are made to be immutable by default.
>>
> It just *can't* be immutable unless all the variables involved are
> implicitly castable to immutable.

In the case of [a, b, c], it either doesn't compile, or is not an  
immutable array.  Because a, b, and c are runtime values (and potentially  
different for every usage of that expression), it makes no sense to make  
them immutable.

In the case of [1, 2, 3], all the items are available at compile-time, and  
an immutable array can be created.

> And what if I need a *mutable* array? .dup it?

Or use a library function that creates a new array from runtime-determined  
elements.  But this problem is already solved, we are talking about static  
arrays, not dynamic arrays.

> My suggestion would be to be consistent with built-in types.

That's fine for static arrays, but the crux of the matter is the syntax.   
Dynamic arrays are inherently reference types.  You cannot simply convert  
them to and from mutable and immutable.  So you either can't have the same  
syntax to initialize dynamic arrays as you have to initialize static  
arrays, or the compiler has to treat the literals for arrays differently  
depending on usage.

There is not one type that an array literal can be that translates  
correctly to dynamic, dynamic immutable, and static arrays.  So the  
compiler could do some magic to make the type special, but it also has to  
behave differently for different uses.  It's a complicated problem to  
solve, and the question is, where does the solution belong, in the library  
or the compiler?

-Steve



More information about the Digitalmars-d mailing list