www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Static initialization of rectangular arrays

reply rombankzero <bogomancer gmail.com> writes:
Hey, everybody! I'm having Array Problems™. The documentation on 
arrays says that you can initialize all elements of a rectangular 
array with the following syntax:

 double[6][3] matrix = 0; // Sets all elements to 0.
However this doesn't appear to work for static initialization:
 static double[6][3] matrix = 0; // Error: cannot implicitly 
 convert expression `0` of type `int` to `double[6][3]`
More confusingly, it *does* work for one-dimensional static arrays:
 static double[6] matrix = 0; // Thumbs up from the compiler.
Is this a bug, or am I missing something? It would be really convenient to be able to statically initialize rectangular arrays in this way. Example: I have a struct that has a member that's a rectangular float array, but I have no way of telling the compiler that I want it default-initialized to all-zeroes (instead of NaNs)!
Aug 29 2019
parent reply Les De Ridder <les lesderid.net> writes:
On Thursday, 29 August 2019 at 15:10:26 UTC, rombankzero wrote:
 [...]

 Is this a bug, or am I missing something? It would be really 
 convenient to be able to statically initialize rectangular 
 arrays in this way. Example: I have a struct that has a member 
 that's a rectangular float array, but I have no way of telling 
 the compiler that I want it default-initialized to all-zeroes 
 (instead of NaNs)!
It's a known bug[1]. As a workaround you could use a `static this()`: static double[6][3] matrix; static this() { matrix = 0; } [1] https://issues.dlang.org/show_bug.cgi?id=19178
Aug 29 2019
parent reply kinke <noone nowhere.com> writes:
On Thursday, 29 August 2019 at 18:11:50 UTC, Les De Ridder wrote:
 It's a known bug[1].

 As a workaround you could use a `static this()`:
Or LDC, and GDC probably too.
Aug 29 2019
parent reply kinke <noone nowhere.com> writes:
On Thursday, 29 August 2019 at 18:59:22 UTC, kinke wrote:
 On Thursday, 29 August 2019 at 18:11:50 UTC, Les De Ridder 
 wrote:
 It's a known bug[1].

 As a workaround you could use a `static this()`:
Or LDC, and GDC probably too.
Sorry, that was wrt. the linked bugzilla and not this example here. - What does work is `static double[6][3] matrix = [0, 0, 0]`, i.e., initializing each nested 1D array with a scalar 0.
Aug 29 2019
parent rombankzero <bogomancer gmail.com> writes:
On Thursday, 29 August 2019 at 19:06:04 UTC, kinke wrote:
 Sorry, that was wrt. the linked bugzilla and not this example 
 here. - What does work is `static double[6][3] matrix = [0, 0, 
 0]`, i.e., initializing each nested 1D array with a scalar 0.
I guess I'll use this workaround, though obviously it becomes more impractical the larger the outermost array dimension is ¯\_(ツ)_/¯
Aug 29 2019