runtime static arrays

bearophile bearophileHUGS at
Tue Nov 20 16:29:15 PST 2012

Jonathan M Davis:

> Personally though, I wish that the length of static arrays 
> could be set at
> runtime and don't really understand why you can't (aside from 
> the fact that
> you can't in standard C - gcc will let you though).

Variable Length Arrays are part of the standard in C since C99, 
and they are in C11 still.

D doesn't have VLAs, I have asked for them since lot of time. I 
don't know why Walter doesn't like them. After using Ada language 
a little, I believe that stack allocation is very useful when you 
want to write fast code.

VLAs are a little unsafe in D because they are not on the heap, 
but a good type system is able to make them safe (some kind of 
static region analysis, done by the Rust language compiler, not 
present in D).

Beside the problem of memory ownership, and problems with stack 
overflows, there are other problems with VLAs, like how the D 
type system has to denote them, and how to move them around. How 
do you return them? Some considerations:

void foo(int n) {
     int[](n) data; // D VLA syntax?
     static assert(sizeof(data) = sizeof(size_t)); // 1 word?
     static assert(is(typeof(data) == int()));
     bar(data); // OK, decays to dynamic array
     bar(data.dup); // OK, dup turns it on a heap allocated 
dynamic array
     spam(data); // probably not allowed.
void bar(int[] a) {}
void spam(int[10] b) {}
void baz(int() c) {} // not allowed syntax.

Here I have used a different syntax because I think there is a 
problem with using the normal syntax: D performs CTFE when you 
call a function in a context that asks for a compile-time result 
value. Currently static array definitions require a compile-time 
value, so they induce CTFE. If D gains VLAs stack arrays can be 
created with a run-time size too, so how does the compiler knows 
if you want CTFE and to create a fixed array or you want to call 
the function at runtime and create a VLA? A different syntax 
avoids this problem.

VLAs are meant only for automatic variables, you can't put one of 
them in structs or class instances, or in global scope. Also a 
VLA decades in a dynamic array with dup or to fixed size whem 
given to a function with fixed sized argument, so you can't pass 
VLA around.

One advantage of VLA is a less bug-prone syntax compared to 
alloca(), expecially when you want 2D, 3D, etc VLA array.

C++11 has not introduced VLA for unclear reasons, but probably 
one reason was to not add more complexities. In the D type system 
there are dynamic arrays, so the situation is better.

Maybe some kind of VLAs will be present in C++14, according to 
what the C++ committee says.


More information about the Digitalmars-d-learn mailing list