Bug 14944 – [REG2.064] cannot initialize static array by static this()

Status
RESOLVED
Resolution
FIXED
Severity
regression
Priority
P1
Component
dmd
Product
D
Version
D2
Platform
All
OS
All
Creation time
2015-08-21T07:28:05Z
Last change time
2020-03-21T03:56:42Z
Keywords
pull, wrong-code
Assigned to
No Owner
Creator
yosikawa

Comments

Comment #0 by yosikawa — 2015-08-21T07:28:05Z
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
Comment #4 by k.hara.pg — 2015-09-01T12:37:55Z
Comment #5 by github-bugzilla — 2015-09-02T06:45:34Z
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()
Comment #6 by github-bugzilla — 2015-09-06T12:04:50Z