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

John Colvin via Digitalmars-d digitalmars-d at puremagic.com
Mon Apr 13 10:17:38 PDT 2015


On Monday, 13 April 2015 at 17:05:59 UTC, BS & LD wrote:
> On Monday, 13 April 2015 at 17:02:13 UTC, CraigDillabaugh wrote:
>> On Monday, 13 April 2015 at 16:53:55 UTC, BS & LD wrote:
>>> As you know in 'C' you can create a variable-length-array 
>>> using variably modified type and a run-time variable 
>>> allocating a storage for it - the same way for any local 
>>> (normally using the stack).
>>>
>>> However in 'D' I don't see such feature. Code like this fails:
>>>
>>> void main()
>>> {
>>>   size_t szArr = 3;
>>>
>>>   int[szArr] arr;
>>> }
>>>
>>> With this error message:
>>>
>>> error: variable szArr cannot be read at compile time
>>>    int[szArr] arr;
>>>
>>> Life example - 
>>> http://melpon.org/wandbox/permlink/a6CzBhYk88FohKlf
>>>
>>> Note:  I'm also amazed why 'D' compiler can't detect that 
>>> 'szArr' is a constant anyway.

It can, but allowing any variable that happens to be determined 
at compile-time to be used by other compile-time constructs just 
doesn't scale, especially with D's extensive meta-programming 
abilities.

>> int[] arr;
>> arr.length = 3;
>
> I suppose this will allocate the array on the 'heap' or it's 
> storage will last past the function scope doesn't it?
>
> What I want is to allocate such variable-length-array on the 
> stack as any other local variable.

You can use alloca to get this effect:

import core.stdc.stdlib: alloca;
void main()
{
	int s = 4;
	auto arr = (cast(float*)alloca(s))[0..s];
	arr[] = 5;
	assert(arr == [5,5,5,5]);
}

It's not pretty, but it works.


More information about the Digitalmars-d mailing list