One case of array assignments

monarch_dodra monarchdodra at gmail.com
Mon Mar 18 14:45:54 PDT 2013


On Monday, 18 March 2013 at 21:35:43 UTC, Chris Nicholson-Sauls 
wrote:
> On Thursday, 14 March 2013 at 01:34:02 UTC, Marco Leise wrote:
>> Am Wed, 13 Mar 2013 14:31:42 -0700
>> schrieb "H. S. Teoh" <hsteoh at quickfur.ath.cx>:
>>
>>> Why is it bad to have to explicitly list the elements for 
>>> static
>>> initialization?
>>
>> Because of:
>>
>> struct CompressionData
>> {
>> 	ubyte[4096] x =
>> [0,0,0 /* ...ad nauseum... */ ,0,0];
>> }
>
> struct CompressionData
> {
>     ubyte[4096] x; // note this is already [0...0] thanks
>                    // to default init... but still:
>
>     this ()
>     {
>         x[] = 0;
>     }
> }

The downside here is that this requires run-time initialization.

> --- Or even: ---
>
> import std.range;
>
> struct CompressionData
> {
>     ubyte[4096] x = repeat( 0 )[ 0 .. 4096 ];
> }
>
> Assuming repeat()[] is CTFE-able (didn't test).

Better, but that doesn't compime, because "repeat( 0 )[ 0 .. 4096 
]" is not an actual array, but a complex type. And of type int. 
The correct code would be:

ubyte[4096] x = repeat( cast(ubyte)0 )[ 0 .. 4096 ].array();

This can be used as-is inside normal code. Hwoever, array is not 
CTFE-able, so it can't work to define a struct T.init value.


More information about the Digitalmars-d mailing list