Does 'D' language supports 'C' like VLA?
BS & LD via Digitalmars-d
digitalmars-d at puremagic.com
Mon Apr 13 10:34:14 PDT 2015
On Monday, 13 April 2015 at 17:24:38 UTC, Steven Schveighoffer
wrote:
> On 4/13/15 12:53 PM, 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, it's best to show when comparing C/C++ to D the C++ code
> and how you expect it to work too.
>
> I experimented a bit with C++ to see what it will do:
>
> #include <stdio.h>
>
> int main(int argc, char *argv[])
> {
> int arr[argc];
> int i;
> printf("i: %p, arr[0]: %p\n", &i, &arr[0]);
> }
>
> Which makes the array completely variable size depending on
> argc (a runtime variable). The results surprised me a bit:
>
> $ ./testvararray
> i: 0x7fff5aeadb5c, arr[0]: 0x7fff5aeadb30
> $ ./testvararray a
> i: 0x7fff5a955b4c, arr[0]: 0x7fff5a955b20
> $ ./testvararray a b
> i: 0x7fff5854eb4c, arr[0]: 0x7fff5854eb20
> $ ./testvararray a b c
> i: 0x7fff5fb12b3c, arr[0]: 0x7fff5fb12b10
> $ ./testvararray a b c d
> i: 0x7fff528e1b2c, arr[0]: 0x7fff528e1af0
>
> So the code will move i around depending on arr size. It's
> consistent between runs as well, if you pass the same number of
> args. I didn't expect that, but I wasn't sure exactly what I
> expected :)
>
> D doesn't do this, you have to know the size of the stack array
> at compile time. You can use alloca, which will give you some
> runtime allocation of stack, but it can be dangerous (as noted).
>
I don't know how things are handled here but it will be very nice
if someone could make the language support this.
>>
>> Note: I'm also amazed why 'D' compiler can't detect that
>> 'szArr' is a
>> constant anyway.
>
> Value range propagation (the compiler understanding what values
> a variable can be at some point in time) only is inside one
> statement. It does not remember what szArr can be at a later
> statement.
>
> -Steve
Although I think it will be a nice feature if it can. I would
prefer slower compilation then slower code.
More information about the Digitalmars-d
mailing list