How to detect if an array if dynamic or static
sigod via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu Feb 25 04:42:12 PST 2016
On Thursday, 25 February 2016 at 12:18:07 UTC, mahdi wrote:
> On Thursday, 25 February 2016 at 11:50:02 UTC, sigod wrote:
>> On Thursday, 25 February 2016 at 10:03:08 UTC, mahdi wrote:
>>> Thanks.
>>>
>>> So when we define the function, we MUST specify the array
>>> size to be able to accept a static array?
>>> Can't we just define a function which can accept any static
>>> array with any size? (e.g. a function to calculate average of
>>> a static int array of any size)?
>>
>> Static array can be accepted in place of dynamic:
>>
>> void foo()
>> {
>> int[3] arr = [1, 2, 3];
>>
>> bar(arr);
>> }
>>
>> void bar(scope int[] arr)
>> {
>> import std.stdio : writeln;
>> writeln(arr); // [1, 2, 3]
>> }
>>
>> But be careful not to escape such variables. Demonstration:
>> http://dpaste.dzfl.pl/613e04d4fe3f
>
> My question: If in your `bar` function, the code tries to add a
> new element to the dynamic array, it will be completely ok
> because array is dynamic. BUT if we pass a static array to this
> function, can this error be detected at compile time (and
> prevent a runtime error)? If so, how?
I'm not sure if this is an error at all. Append sees that array
doesn't have any available space and allocates new array.
writeln(arr.ptr); // 7FBFC45AA0
arr ~= 1;
writeln(arr.ptr); // 4002E000
I would say that you have poor code design if your function must
be able to accept static arrays and append elements to it.
You might find this useful:
http://dlang.org/phobos/std_array.html#.Appender
More information about the Digitalmars-d-learn
mailing list