static array literal syntax request: auto x=[1,2,3]S;

Jonathan M Davis jmdavisProg at gmx.com
Sun Jun 10 14:43:29 PDT 2012


On Sunday, June 10, 2012 23:23:57 Mehrdad wrote:
> I honestly don't see the POINT of having a "dynamic array
> literal".
> 
> What's the point of making the literals dynamic?
> 
> They should all be static, and only converted to dynamic if
> necessary from the context.
> 
> But I really don't see the benefit of allocating them on the heap
> just because we can... perhaps someone can enlighten me?

In the vast majority of cases where an array literal is used, it's assigned to 
a dynamic array. And if you do something like

auto arr = [1, 2, 3, 4, 5];

the expectation is that you'll get a dynamic array. So, it's quite natural to 
make array literals dynamic. Almost all arrays are dynamic.

As annoying is it may be upon occasion to not be able to simply pass a literal 
to a templated function which you want to be taking a static array, it would 
be _far_ more annoying if it assumed that the literal were static. Almost all 
functions (templated or otherwise) which take arrays take dynamic ones, not 
static ones.

And if an array literal were static, what would this do?

int[] func(int[] a)
{
    return a;
}

func([1, 2, 3, 4, 5]);

would it slice the static array literal and therefore return a slice of a now 
invalid temporary, or would it allocate the array on the heap as it would now? 
With all other static arrays, you'd get a slice, which would be very much the 
_wrong_ thing to do here. So, making the literal static and then slicing it 
wuold be very bad, but making it static and then converting it to a dynamic 
array would be completely inconsistent with the normal case.

About the only case where it's obvious what it should be doing is

int[5] a = [1, 2, 3, 4, 5];

Pretty much the only reason that this causes any problems is the case where 
you want to initialize a static array with a literal. In virtually _all_ other 
cases, what you want is a dynamic array, and making it a static one would just 
cause problems in many of them.

As such, this particular case should just be handled specially and optimize 
out the heap allocation rather than trying to alter how the literals 
themselves work. We already get that with strings. A string literal defaults 
to string, but you can pass it to a function taking wstring or dstring or 
assign it to a wstring or dstring variable. The compiler takes care of the 
conversion for you. So, assigning a static array with a literal would just be 
another case like that.

But since what you almost always want is a dynamic array, making the literal 
itself static would be asking for a heap of trouble.

- Jonathan M Davis


More information about the Digitalmars-d mailing list