Does 'D' language supports 'C' like VLA?
via Digitalmars-d
digitalmars-d at puremagic.com
Mon Apr 13 12:29:46 PDT 2015
On Monday, 13 April 2015 at 19:10:28 UTC, Steven Schveighoffer
wrote:
> It would be nice if alloca could be wrapped so it could be made
> safe(r).
string stackArray(T)(string name, string len) {
import std.format : format;
return q{
import core.stdc.stdlib : alloca;
import std.conv : emplace;
size_t %2$s_length_ = %3$s;
%1$s* %2$s_storage_ = cast(%1$s*) alloca(%2$s_length_ *
%1$s.sizeof);
%1$s[] %2$s = %2$s_storage_[0 .. %2$s_length_];
foreach(ref ele; %2$s)
emplace(&ele);
}.format(T.stringof, name, len);
}
void main(string[] args)
{
import std.conv : to;
import std.stdio : writefln;
mixin(stackArray!int("arr", q{ args[1].to!size_t }));
writefln("allocated an array of %s bytes", arr.length);
writefln("arr = %s", arr);
}
This is the best I can come up with currently. I think with a
@forceinline attribute, it would be a lot better, assuming
`alloca()` is usable inside an inlined method.
More information about the Digitalmars-d
mailing list