I have stumbled upon an issue when working with arrays in D. I need to initialize an array with an arbitrary number of elements of a pre-defined value.
I know it can be done like double[10] arr = 5;
, for example, this will make an array with 10 elements of value 5. The problem, however, is that I need the number of elements passed on during the program's execution. I thought it could be done this way:
void test(immutable int x)
{
double[x] arr = 5;
writeln(arr);
}
void main() { test(10); }
But this causes Error: variable x cannot be read at compile time
during compilation.
While it could be done by making a dynamic array and appending elements through a for
loop, I think this may be rather inefficient (please correct me if I am wrong). So the question is, is there another efficient way to create an array with an arbitrary number of elements?