Search code examples
d

Does 'D' language supports 'C' like VLA?


Does 'D' language supports locally-allocated 'C' like variable-length-arrays?

Something like this:

void main()
{
    size_t szArr = 3;

    int[szArr] arr;
}

Solution

  • Nope, not with runtime variables like that. You'd need to use an alternative:

    • alloca can allocate runtime sized stack space, just like in C, then you slice it.

      int[] a = (cast(int*) alloca(size * int.sizeof))[0 .. size];
      

    That can not be abstracted into a function due to how alloca works. You could make it a mixin string though.

    • You could use a static array, like said in the other answer, then slice it to a size. Something like:

      int[1024] buffer;
      int[] runtimeSized = size <= buffer.length ? buffer[0 .. size] : (new int[](size);
      

    Since the buffer is statically sized, you slice it if you can, then make a regular array if not (or you could throw a "Data too big" exception of some sort).

    You can abstract this into a nice little struct for easier use if you like.

    Remember that storing a reference to stack data after the function returns is invalid, but the compiler won't help much in pointing out where you did it.