www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Function Error: cannot be read at compile time

reply "jmh530" <john.michael.hall gmail.com> writes:
I'm trying to run the following code (to create an array of 
uniform random variables) on the latest version of rdmd (2.067.1).

import std.random;

auto uniform_array(int len, float a, float b) {
	Random gen;
	float output[len];
	foreach(ref float i; output)
	{
		i = uniform(a, b, gen);
	}
	return output;
}

void main() {
	auto val2 = uniform_array(10, 0.0f, 1.0f);
}

But I get the error
testing_some_stuff.d(5): Error: variable len cannot be read at 
compile time
Failed: ["dmd", "-v", "-o-", "testing_some_stuff.d", "-I."]

I'm not sure why this is an error. The code worked before I put 
it into a function. The function seems to work when I hardcode in 
a length. It's only having some variable length that's a problem. 
I'm not sure why.
Jun 04 2015
parent reply "Alex Parrill" <initrd.gz gmail.com> writes:
On Thursday, 4 June 2015 at 17:04:06 UTC, jmh530 wrote:
 	float output[len];
This creates a fixed-sized array of length `len` (using the deprecated syntax). Since the length is part of the type, it needs to be known at compile time. You probably want a dynamic array instead. `auto output = new float[len]` Also note that you're not seeding your random number generator, so it will produce the same sequence every time. You probably want `auto gen = Random(unpredictableSeed);`
Jun 04 2015
parent "jmh530" <john.michael.hall gmail.com> writes:
On Thursday, 4 June 2015 at 17:25:52 UTC, Alex Parrill wrote:
 On Thursday, 4 June 2015 at 17:04:06 UTC, jmh530 wrote:
 	float output[len];
This creates a fixed-sized array of length `len` (using the deprecated syntax). Since the length is part of the type, it needs to be known at compile time. You probably want a dynamic array instead. `auto output = new float[len]` Also note that you're not seeding your random number generator, so it will produce the same sequence every time. You probably want `auto gen = Random(unpredictableSeed);`
Thanks for the reply. Changing to a dynamic array works. I think I need to read a bit more on the difference between static and dynamic arrays. It seems like you avoid some of these issues if you pass the array that you want to fill up into the function. I could pass either a static or dynamic array in that case. On the seeding thing, I know that it was doing that, I just wanted to focus on the part that wasn't working.
Jun 04 2015