Stack-allocated arrays

dsimcha dsimcha at yahoo.com
Tue Nov 11 10:36:53 PST 2008


== Quote from Denis Koroskin (2korden at gmail.com)'s article
> I would *LOVE* to see Variable-Length Arrays in D (they are implemented in
> C99)
> void foo(int i)
> {
>     int[i] myArray; // this is a static stack-allocated array (size can't
> be changed)
>     assert(myArray.length() == i);
> }

Yes, a few people have said this in the past.  I'm suggesting something a little
more than that.  I'm saying that, to make this relatively safe, the compiler
automatically "does the right thing" depending on how large an array you are
allocating.  If it's big enough to risk overflowing the stack, then it does heap
allocation.
Better yet, if the array is large, it does heap allocation *and* deletes the array
for you at any exit points of the function so that the GC doesn't run as much,
since the lifetime of the array is known at compile time.



More information about the Digitalmars-d mailing list