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

Jonathan M Davis jmdavisProg at gmx.com
Sun Jun 10 17:57:32 PDT 2012


On Monday, June 11, 2012 02:45:00 Mehrdad wrote:
> On Monday, 11 June 2012 at 00:16:48 UTC, Jonathan M Davis wrote:
> > auto found = find(arr, [1, 2]);
> > 
> > wouldn't compile, because [1, 2] would be considered a static
> > array, which
> > isn't a range.
> > 
> > - Jonathan M Davis
> 
> Uh... that's pretty much just saying, "code that explicitly
> depends on the current behavior would now break".
> 
> 
> Which is true, except that IMHO it's the code's fault.
> 
> 
> The problem is there right now /anyway/:
> int[2] items = [1, 2];
> int[] arr = ...;
> find(arr, items);   // "broken"... but, really, it _should_ work
> 
> 
> So if that's a problem, then it's obviously a problem with find()
> -- it should slice the input -- not with this proposal.

Actually, having it slice the input is arguably a _bad_ idea. You risk stuff 
like

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

int[] bar()
{
    int[5] a = [1, 2, 3, 4, 5];
    return foo(a);
}

b now refers to garbage. Honestly, I think that the fact that static arrays 
_ever_ slice implicitly was a _bad_ design decision and is just asking for 
trouble. If the programmer has to state it explicitly, then they always know 
that they're slicing it rather than copying it, and you reduce the risk of 
having slices to static arrays which don't exist anymore. IMHO, the fact that 
range-based functions don't work with static arrays without slicing them 
automatically is  _good_ thing.

And if all range-based functions were altered to work with static arrays, and 
we made array literals static, then this example would _still_ be broken

auto found = find(arr, [1, 2]);

But instead of giving a compilation error like it would if we just made array 
literal state, instead you're operating on garbage, and you get undefined 
behavior.

If the compiler is changed so that it elides the heap allocation when 
assigning an array literal to a dynamic array, then that solves the problem 
quite cleanl. I don't see how changing array literals to be static would help 
anything. Instead of getting unnecessary heap allocations, you get functions 
that don't work with array literals and/or you end up operating on garbage.

- Jonathan M Davis


More information about the Digitalmars-d mailing list