Debug help - static foreach - module scope - Programming in D page 603
Brother Bill
brotherbill at mail.com
Thu Aug 28 13:33:09 UTC 2025
On Thursday, 28 August 2025 at 13:16:26 UTC, Andy Valencia wrote:
> On Thursday, 28 August 2025 at 13:09:21 UTC, Brother Bill wrote:
>> Unable to compile. Please advise.
>> ```
>> c:\dev\D\81 -
>> 90\c83_e_static_foreach_fibonacci\source\app.d(8): Error:
>> function declaration without return type. (Note that
>> constructors are always named `this`)
>> writeln(n);
>
> writeln() isn't valid at scope 0, which is where that static
> foreach is putting it. I changed it to pragma(msg, n) and saw
> the expected sequence of numbers.
>
> Andy
What is "scope 0"? is this same thing as module scope?
Refactored source/app.d
Output to console: Why does static foreach run 'twice'?
```
pragma: 0
pragma: 2
pragma: 8
pragma: 34
pragma: 0
pragma: 2
pragma: 8
pragma: 34
main(): 0
main(): 2
main(): 8
main(): 34
```
source/app.d
```
import std.stdio;
import std.range;
import std.algorithm;
static foreach (n; FibonacciSeries().take(10).filter!isEven)
{
// writeln not valid as module level (scope 0)
pragma(msg, "pragma: ", n);
}
void main()
{
foreach (n; FibonacciSeries().take(10).filter!isEven) {
writeln("main(): ", n);
}
}
bool isEven(int n) {
return n % 2 == 0;
}
struct FibonacciSeries
{
int current = 0;
int next = 1;
enum empty = false;
int front() const
{
return current;
}
void popFront()
{
const nextNext = current + next;
current = next;
next = nextNext;
}
FibonacciSeries save() const
{
return this;
}
}
```
More information about the Digitalmars-d-learn
mailing list