Issue 14944 - [REG2.064] cannot initialize static array by static this()
Summary: [REG2.064] cannot initialize static array by static this()
Status: RESOLVED FIXED
Alias: None
Product: D
Classification: Unclassified
Component: dmd (show other issues)
Version: D2
Hardware: All All
: P1 regression
Assignee: No Owner
URL:
Keywords: pull, wrong-code
Depends on:
Blocks:
 
Reported: 2015-08-21 07:28 UTC by yosikawa
Modified: 2020-03-21 03:56 UTC (History)
3 users (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description yosikawa 2015-08-21 07:28:05 UTC
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 basile-z 2015-08-21 08:46:38 UTC
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 Jonathan M Davis 2015-08-21 15:41:42 UTC
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 Vladimir Panteleev 2015-09-01 10:31:23 UTC
This is a regression.

Introduced in https://github.com/D-Programming-Language/dmd/pull/2665
Comment 5 github-bugzilla 2015-09-02 06:45:34 UTC
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 github-bugzilla 2015-09-06 12:04:50 UTC
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