Variable "i" can not be read at compile time
bauss
jj_1337 at live.dk
Sun May 24 17:29:38 UTC 2020
On Sunday, 24 May 2020 at 17:13:23 UTC, data pulverizer wrote:
> On Sunday, 24 May 2020 at 16:57:54 UTC, ag0aep6g wrote:
>> On 24.05.20 18:34, data pulverizer wrote:
>> Since `kernel` is a `Tuple`, you can only access it with
>> compile-time constant indices.
>>
>> But your loop variable `i` is not a compile-time constant,
>> it's being calculated at run time. What's more, it depends on
>> `results.length` which is also not a compile-time constant.
>> But `results.length` is the same as `kernels.length`. And
>> being the length of a `Tuple`, that one is a compile-time
>> constant.
>>
>> So you can rewrite your loop as a `static foreach` (which is
>> evaluated during compile-time) using `kernels.length` instead
>> of `results.length`:
>>
>> static foreach (i; 1 .. kernels.length)
>> {
>> results[i] = bench(kernels[i], n, verbose);
>> }
>
> Thank you very much. I though that if I used a `static foreach`
> loop D would attempt to run the calculation `bench()` at
> compile time rather than at run time but it doesn't which is
> good. So `static foreach` allows you to index at compile time
> and if its scope runs at run time it is run time and if at
> compile time it is compile time evaluated?
You can see static foreach as unrolling a compile-time loop to a
set of runtime-expressions.
Ex.
static foreach (i; 0 .. 10)
{
writeln(i);
}
Actually just becomes
writeln(0);
writeln(1);
writeln(2);
writeln(3);
writeln(4);
writeln(5);
writeln(6);
writeln(7);
writeln(8);
writeln(9);
- It creates no scope, whatsoever either. However doing
static foreach ()
{{
...
}}
Will create a scope per iteration.
More information about the Digitalmars-d-learn
mailing list