October 10, 2017 Re: initializing a static array | ||||
---|---|---|---|---|
| ||||
Attachments:
| https://run.dlang.io/is/SC3Fks |
October 10, 2017 Re: initializing a static array | ||||
---|---|---|---|---|
| ||||
Posted in reply to Simon Bürger | On 10/10/2017 03:36 PM, Simon Bürger wrote:
> I have a static array inside a struct which I would like to be initialized to all-zero like so
>
> struct Foo(size_t n)
> {
> double[n] bar = ... all zeroes ...
> }
>
> (note that the default-initializer of double is nan, and not zero)
>
> I tried
>
> double[n] bar = 0; // does not compile
Works for me:
----
struct Foo(size_t n)
{
double[n] bar = 0;
}
void main()
{
import std.stdio;
Foo!5 foo;
writeln(foo.bar); /* prints "[0, 0, 0, 0, 0]" */
}
----
|
October 10, 2017 Re: initializing a static array | ||||
---|---|---|---|---|
| ||||
Posted in reply to Simon Bürger | On Tuesday, 10 October 2017 at 14:15:07 UTC, Simon Bürger wrote: > On Tuesday, 10 October 2017 at 13:48:16 UTC, Andrea Fontana wrote: >> Maybe: >> >> double[n] bar = 0.repeat(n).array; > > This works fine, thanks a lot. I would have expected `.array` to return a dynamic array. But apparently the compiler is smart enough to know the length. Even the multi-dimensional case works fine: > > double[n][n] bar = 0.repeat(n).array.repeat(n).array; I hope this is not performance-critical code. The assembly is terrible for such code, at least for LDC, doing a GC allocation, unrolled reset to zero, then memcpying the dynamic array back to the stack: https://godbolt.org/g/uXBN75 `double[n] bar = void; bar[] = 0;` (2 lines, granted) results in a memset. |
Copyright © 1999-2021 by the D Language Foundation