How to initialize static arrays with variable data
Denis Koroskin
2korden at gmail.com
Fri Feb 19 09:53:56 PST 2010
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.
>
> -Steve
It just *can't* be immutable unless all the variables involved are
implicitly castable to immutable.
And what if I need a *mutable* array? .dup it?
My suggestion would be to be consistent with built-in types. See the
following examples:
auto x1 = 1; // defaults to int, not immutable int
immutable auto x2 = 1; // but immutable also fine
// typeof(x2) = immutable(int)
int a = 42;
immutable auto x3 = a; // you can also construct immutable from a mutable
// variable, if it is implicitly castable to one
Similarly:
auto x1 = [1]; // int[1]
immutable auto x2 = [1]; // immutable(int)[1]
int a = 42;
immutable auto x3 = [a]; // immutable(int)[1]
More information about the Digitalmars-d
mailing list