char[][] titles = (" ", "C", "!", "Description", "Resource", "In Folder", "Location","foo" );

Oskar Linde oskar.lindeREM at OVEgmail.com
Sat Mar 1 15:16:05 PST 2008


Bill Baxter wrote:
> John C wrote:
>> Jarrett Billingsley wrote:
>>> "Bill Baxter" <dnewsgroup at billbaxter.com> wrote in message 
>>> news:fqau6f$1565$1 at digitalmars.com...
>>>
>>>> I think that does it.  If not maybe you have to use the [] on all of 
>>>> the strings.  I don't recall.
>>>
>>> Just the first.
>>>
>>
>> Using DMD 1.027 it compiles without resorting to that trick on any 
>> element.
> 
> Huh.  Coulda sworn that didn't used to work, but it seems like it was 
> working at least as far back as dmd 1.0.

There is a difference how this works between array initializers, type 
inferred array initializers and array literals. The above doesnt work if 
you change char[][] into auto. Examples:

This is an array initializer:

(a) char[][] titles = ["a", "bb"];

this is a type inferred array initializer:

(b) auto titles = ["a","bb"];

and this is an array literal:

(c) auto titles = (["a","bb"]);

The rules are slightly different in those cases. In DMD 1.020 (sans a 
couple of bugs) it works like this:

In (a), the type of the initializer is known in advance, and each 
element of the initializer is implicitly converted to the element type 
of the array. In (b), the type is first inferred from the initializer 
(as an array of the the type of the first element) and then each element 
is implicitly converted like in (a). In (c), the initializer is instead 
interpreted as an array literal which has a subtle difference from case 
(b): If the first element of an array literal is a static array, it is 
converted to a dynamic array.

The result is that (a) and (c) compiles, while (b) doesn't(*).

*) Depends on compiler version. DMD 2.010 and 2.011 actually compiles 
but gives incorrect code generation(!):

auto titles = ["a","bb"];
writefln(titles);
Prints [a b] (!)
typeof(titles) is invariant(invariant(char)[1])[2]

(c) and (a) prints [a bb] as it should.

-- 
Oskar


More information about the Digitalmars-d-learn mailing list