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]); }
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 } ---
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.
This is a regression. Introduced in https://github.com/D-Programming-Language/dmd/pull/2665
https://github.com/D-Programming-Language/dmd/pull/5013
Commits pushed to stable at https://github.com/D-Programming-Language/dmd https://github.com/D-Programming-Language/dmd/commit/1d621e240a0f8d7df60fb1c7f14da21532aa99d5 fix Issue 14944 - cannot initialize static array by static this() https://github.com/D-Programming-Language/dmd/commit/e6e75a6892fc63307f940e867c0fcdc55406cf9d Merge pull request #5013 from 9rnsr/fix14944 [REG2.064] Issue 14944 - cannot initialize static array by static this()
Commits pushed to master at https://github.com/D-Programming-Language/dmd https://github.com/D-Programming-Language/dmd/commit/1d621e240a0f8d7df60fb1c7f14da21532aa99d5 fix Issue 14944 - cannot initialize static array by static this() https://github.com/D-Programming-Language/dmd/commit/e6e75a6892fc63307f940e867c0fcdc55406cf9d Merge pull request #5013 from 9rnsr/fix14944