Why is this allowed

Steven Schveighoffer schveiguy at gmail.com
Wed Jul 1 16:16:31 UTC 2020


On 7/1/20 11:57 AM, Nathan S. wrote:
> On Tuesday, 30 June 2020 at 16:22:57 UTC, JN wrote:
>> Spent some time debugging because I didn't notice it at first, 
>> essentially something like this:
>>
>> int[3] foo = [1, 2, 3];
>> foo = 5;
>> writeln(foo);   // 5, 5, 5
>>
>> Why does such code compile? I don't think this should be permitted, 
>> because it's easy to make a mistake (when you wanted foo[index] but 
>> forgot the []). If someone wants to assign a value to every element 
>> they could do foo[] = 5; instead which is explicit.
> 
> What's your opinion on using that syntax in the initial declaration, 
> like `float[16] foo = 0`?

It's important to keep at least something that allows such setting. It 
would be reasonable to do this with a function as well.

Is it possible to have the initialization syntax work differently from 
the assignment (i.e. allow the initialization as above, but require the 
brackets for assignment)?

-Steve


More information about the Digitalmars-d-learn mailing list