How to detect if an array if dynamic or static

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Feb 24 23:31:26 PST 2016


On 02/24/2016 08:44 PM, mahdi wrote:
 > On Wednesday, 24 February 2016 at 22:38:04 UTC, Adam D. Ruppe wrote:
 >> On Wednesday, 24 February 2016 at 21:48:14 UTC, mahdi wrote:
 >>> How can we detect is `array` is static (fixed size) or dynamic,
 >>> inside the function body?
 >>
 >> `array` there is always dynamic because it is not of a fixed size type.
 >>
 >> Why do you want to know though?
 >
 > I thought we can simply denote `int[] x` in case we have an array
 > argument in D functions. So according to your answer if a function
 > expects a static array, it has to specify size of array in parameter
 > declaration:
 >
 > void diss(int[3] array) ...  //this expects a static array of size 3
 > void diss(int[] array) ...  //this expects a dynamic array
 >
 > is this correct?

Yes.

Note that static arrays are value types. So, if the parameter is int[3], 
then the argument will be copied. However, you can still take it by 
reference (with the ref keyword):

import std.stdio;

void diss(ref int[3] array) {
     writeln(typeof(array).stringof);
}

void diss(int[] array) {
     writeln(typeof(array).stringof);
}

void main() {
     int[3] arr;
     diss(arr);
}

Prints:

int[3]

And a reminder that rvalues cannot be bound to ref in D. So, 'ref 
int[3]' may not be usable in your case.

Ali



More information about the Digitalmars-d-learn mailing list