Variable "i" can not be read at compile time

ag0aep6g anonymous at example.com
Sun May 24 17:34:47 UTC 2020


On 24.05.20 19:13, data pulverizer wrote:
> 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?

`static foreach` gets unrolled at compile time. It doesn't affect how 
the body is handled. It's like copy-pasting the loop body n times in the 
source code.

For example, this:

     int x = 0;
     static foreach (i; 0 .. 3)
     {
         x += f(i);
     }

is the same this:

     int x = 0;
     x += f(0);
     x += f(1);
     x += f(2);

It doesn't affect how `f` is being run. They're ordinary run-time calls 
either way.

To evaluate the `f` calls during compilation you can use `enum` to 
trigger CTFE:

     int x = 0;
     enum f0 = f(0); /* CTFE */
     x += f0;
     enum f1 = f(1); /* CTFE */
     x += f1;
     enum f2 = f(2); /* CTFE */
     x += f2;

or with `static foreach`:

     int x = 0;
     static foreach (i; 0 .. 3)
     {{
         enum e = f(i);
         x += e;
     }}

Notice the extra set of braces. It's just adding a scope. Without that, 
the different `e`s would clash with each other.


More information about the Digitalmars-d-learn mailing list