What's the point of static arrays ?

Paul Backus snarwin at gmail.com
Thu Jul 9 18:51:47 UTC 2020


On Thursday, 9 July 2020 at 18:02:02 UTC, IGotD- wrote:
>
> Static arrays are great because as already mentioned, they are 
> allocated on the stack (unless it is global variable something, 
> then it ends up in the data segment or TLS area).
>
> As C/C++ now allows dynamically sized static arrays (for stack 
> only), shouldn't D allow this as well.
>
> Now you have to do.
>
> import core.stdc.stdlib;
>
> void myFunc(size_t arraySize)
> {
>     void *ptr = alloca(arraySize);
>     ubyte[] arr = cast(ubyte[])ptr[0..arraySize];
>
> }
>
> it would be nice if we could just write
>
> ubyte[arraySize] just like in C.

Note that using VLAs in C is widely considered to be bad 
practice, and that they were made optional in the C11 standard.

If you want to allocate an array on the stack, the best way is to 
use a static array for size below a predetermined limit, and fall 
back to heap allocation if that limit is exceeded. An easy way to 
do this in D is with 
`std.experimental.allocator.showcase.StackFront`.


More information about the Digitalmars-d-learn mailing list