Array literals

Sergey Gromov snake.scaly at gmail.com
Sat Oct 18 07:52:06 PDT 2008


Fri, 17 Oct 2008 16:00:55 -0400,
Nick Sabalausky wrote:
> "bearophile" <bearophileHUGS at lycos.com> wrote in message 
> news:gd9vqi$oos$1 at digitalmars.com...
> > Nick Sabalausky:
> >> I like T[static] a lot. Static might be a highly overloaded word, but the
> >> idea of a "static array" is already one of the firmly established 
> >> overloads.
> >> You want a static array? Say "static". Nice :)
> >
> > +1.
> > I think it's acceptable. So the code equivalent to the original one 
> > becomes (plus the immutable statement):
> >
> > import std.stdio: writefln;
> > void main() {
> >    char[static][static] a = ["Hello", "what"];
> >    writefln(a[2].length); // 5
> > }
> >
> > Most of the times you don't want that so you use:
> >
> > auto a = ["Hello", "what"];
> >
> > Now we can wait for Walter to express his opinion on this improvement of 
> > the language.
> >
> > Bye,
> > bearophile
> 
> As long as we're talking about initializing jagged static arrays, I'd also 
> add one other slight change. The following should also compile (the current 
> D1 equivilent code complains. Not sure about D2):
> 
> // The only change from the code above is
> // swapping the order of "Hello" and "what"
> import std.stdio: writefln;
> void main() {
>     char[static][static] a = ["what", "Hello"];
>     writefln(a[1].length); // 5
> }

Type of an array element is inferred from the first element of a literal, 
it's in the specs.  Also, compiler probably fills the missing elements 
with default initializer so in fact you get

char[static][static] a = ["what\0", "Hello"];

or, for the same result,

char[5][static] a = ["what", "Hello"];

It'd probably be nice if, for arrays of static arrays, compiler 
automatically picked the longest inner array for the purposes of outer 
array's element type inferring.



More information about the Digitalmars-d mailing list