What's the point of static arrays ?

wjoe invalid at example.com
Fri Jul 10 10:13:23 UTC 2020

So many awesome answers, thank you very much everyone!

Less overhead,
Using/needing it to interface with something else, and
Efficiency are very good points.

However stack memory needs to be allocated at program start. I 
don't see a huge benefit in allocation speed vs. heap 
pre-allocation, or is there?
I mean 1 allocation vs 2 isn't going to noticeably improve 
overall performance.

On Thursday, 9 July 2020 at 12:48:26 UTC, Simen Kjærås wrote:
> [...]
>> - Can't slice them
>> - Can't range them
> Sure you can:
> unittest {
>     import std.stdio;
>     import std.algorithm;
>     int[10] a = [1,2,3,4,5,6,7,8,9,10];
>     // Note I'm slicing the static array to use in range 
> algorithms:
>     writeln(a[].map!(b => b+2));
> [...]

>     a[]
What happens here exactly ?

I read the chapters in Ali's book (thank you very much for such a 
great book, Ali) on arrays and slicing prior to asking this 
question and I came to the following conclusion:

Because a static array is pre-allocated on the stack,
doesn't have a pointer/length pair,
is addressed via the stack pointer, and
due to the fact that a slice is a pointer/length pair
   and because a slice is technically the meta data of a dynamic 
array, a view into (part) of a dynamic array,
that it's not possible to slice a static array because the slice 
would technically be akin to a dynamic array and hence be 

As for `can't range them` Ali's chapter on ranges emphatically 
stresses the fact that ranges are lazy.
But due to the fact that static arrays are copied, I couldn't see 
how to satisfy the lazy property.

Consider this:

struct SuperSpecializedArray(T, size_t S) if (S > 0)
    T[S] elements;

    struct SuperSpecializedArrayRange
       typeof(elements) e;

       this(SuperSpecializedArray a)
          e = a.elements; // copies

       // ...

Upon creation of a SuperSpecializedArrayRange, the array is 
copied, but more importantly, data which may not ever be needed 
is copied and that's supposed to be a big selling point for 
ranges - only ever touching the data when it's requested - am I 
wrong ?

But considering Simen's answer I now know that a slice of 
elements can be used so that's that.

More information about the Digitalmars-d-learn mailing list