Following code prints "0" using
DMD32 D Compiler v2.068.0
import std.stdio;
class Foo {
static int[10] tbl;
static this() {
foreach(ref v; tbl) {
v = 1;
}
}
}
void main() {
writeln(Foo.tbl[0]);
}
Comment #1 by b2.temp — 2015-08-21T08:46:38Z
The problem is more subtle than suggested by the summary. Actually the problem is the **ref** in foreach().
Initialization of the array succeeds if you use another form of for loop, e.g
---
import std.stdio;
class Foo {
static int[10] tbl;
static this() {
foreach(i; 0 .. tbl.length) {
tbl[i] = 1;
}
}
}
void main() {
writeln(Foo.tbl[0]); // 1
}
---
Comment #2 by issues.dlang — 2015-08-21T15:41:42Z
The same thing happens if it's a module-level static constructor. So, the class doesn't matter. And doing the same assignment to the array with a ref in foreach works in a normal function. It's specifically when that assignment is done in a static constructor that this happens.
My guess is that it stems from the fact that if a variable is initialized is a static constructor, then it's not supposed to be initialized before that (otherwise, you couldn't initialize const or immutable variables that way), but I don't know.
Comment #3 by dlang-bugzilla — 2015-09-01T10:31:23Z