Array literals' default type

Steven Schveighoffer schveiguy at yahoo.com
Thu Oct 8 12:50:31 PDT 2009


On Thu, 08 Oct 2009 15:10:46 -0400, Denis Koroskin <2korden at gmail.com>  
wrote:

> On Thu, 08 Oct 2009 22:07:32 +0400, Andrei Alexandrescu  
> <SeeWebsiteForEmail at erdani.org> wrote:
>
>> Consider:
>>
>> auto c = [ 2.71, 3.14, 6.023e22 ];
>> c ~= 2.21953167;
>>
>> Should this work? Currently it doesn't because c's type is deduced as  
>> double[3].
>>
>> The literal can initialize either double[3] or double[], so the  
>> question is only what the default should be when "auto" is used.
>>
>>
>> Thoughts?
>>
>> Andrei
>
> I was just about to bump a similar topic.
>
> I strongly believe typeof(c) must be immutable(double)[3].

You're half right.  It should be immutable(double)[].

Remember, double[3] is allocated *on the stack*, so there is no point in  
making it immutable.

So the only two logical choices are:

double[3] - The compiler stores a copy of this array somewhere, and  
initializes the stack variable with the contents each time the literal is  
used (or generates code to make the array in the function itself).

immutable(double)[] - The compiler stores a copy of this array somewhere  
in ROM and initializes the stack variable with the immutable pointer to  
the data.

The second choice is almost certainly more useful than the first, and if  
you truly don't need it mutable, much better performing.

This then leaves the quandry -- what if you *do* want a static array, but  
you don't want to have to match the size?  I think bearophile's suggestion  
is a good one:

double[$] c = ...

Or another option:

auto[$] c = ...

if you want true type inference from the literal.

> 2) There is an inconsistency with strings:
>
>      auto c1 = "Hello"; // immutable
>      auto c2 = ['H', 'e', 'l', 'l', 'o']; // mutable
>

Note that the type of c1 is not immutable(char)[5], it's immutable(char)[]  
(this is different from D1, where the "Hello" literal would be typed  
char[5u]).

-Steve



More information about the Digitalmars-d mailing list