Fixed size array initialization

b2.temp at gmx.com b2.temp at gmx.com
Sat Feb 10 14:55:49 UTC 2018


On Saturday, 10 February 2018 at 14:35:52 UTC, rumbu wrote:
> On Saturday, 10 February 2018 at 12:28:16 UTC, b2.temp wrote:
>> On Saturday, 10 February 2018 at 10:55:30 UTC, rumbu wrote:
>>> I know that according to language spec 
>>> (https://dlang.org/spec/arrays.html#static-init-static) you 
>>> can skip declaring all your elements in a fixed size array.
>>>
>>> I'm just recovering from a bug which took me one day to 
>>> discover because of this.
>>>
>>> I have a large static initialized array, let's say int[155], 
>>> and I forgot to declare the last element:
>>>
>>> int[155] myarray = [
>>>   a,
>>>   b,
>>>   c,
>>>   ...
>>>   //forgot to declare the 155th element
>>> ];
>>>
>>> I took for granted that the compiler will warn me about the 
>>> fact that my number of elements doesn't match the array 
>>> declaration but I was wrong.
>>>
>>> Does it worth to fill an enhancement on this, or this is 
>>> intended behavior?
>>
>> I used to agree 
>> (https://issues.dlang.org/show_bug.cgi?id=17341) and even 
>> patched the compiler
>>to emit a deprecation in this case. Then
>> i discovered that druntime for example relies on this.
>>
>> The classic use case is to init a LUT where only a few 
>> elements need a non-default value, for example:
>>
>> ```
>> bool[char.max] lut = [10:true, 13:true, 9: true];
>> assert(!lut[46]);
>> assert(lut[9]);
>> ```
>>
>> which can be useful.
>
> In this case, it there any way to be sure that I declared all 
> the elements I intended? Obviously, without counting them by 
> hand.

At the level of the library use a template.

At the level of the compiler: no. Not only not all elements are 
required but they also don't need to be declared in order (static 
array initialization, like in the example beyond).

It would be possible to put a compiler warning but warnings are 
not in the D philosophy (one consequence is that many people, 
like me use -de all the time, making a possible warning not 
compatible with the legit uses of the "partial array 
initialization").

By the way i said i did change the compiler. Actually i even 
captured the session to promote my IDE: 
http://sendvid.com/c00x7nps.


More information about the Digitalmars-d-learn mailing list