How to detect if an array if dynamic or static
mahdi via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu Feb 25 04:18:07 PST 2016
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?
More information about the Digitalmars-d-learn
mailing list