Array literals' default type

Denis Koroskin 2korden at gmail.com
Thu Oct 8 13:43:57 PDT 2009


On Thu, 08 Oct 2009 23:50:31 +0400, Steven Schveighoffer  
<schveiguy at yahoo.com> wrote:

> 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.
>

Right, that was an oversight. I'm now in favor of immutable(double)[].

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

I believe the two should be the same (with the tiny difference that c1 is  
null-terminated under the hood), immutable(char)[] that is.



More information about the Digitalmars-d mailing list