default initialization of char arrays
6622
notanemail at foo.fake
Wed Oct 22 16:35:47 UTC 2025
On Wednesday, 15 October 2025 at 15:22:14 UTC, monkyyy wrote:
> On Wednesday, 15 October 2025 at 11:51:05 UTC, Quirin Schroll
> wrote:
>> On Monday, 8 September 2025 at 15:42:27 UTC, Walter Bright
>> wrote:
>>> […]
>>>
>>> A `char` default initializes to `0xFF`. The programmer wanted
>>> to default initialize the array of char to `0`, and so used
>>> `[0]` to initialize it. This resulted in
>>> `[0,255,255,255,255,255,255,255,255,255]`. He asked how to
>>> default initialize it to `0` without having to tediously
>>> enumerate the `0` for each element in the initializer.
>>
>> Please make this footgun an error. The compiler can tell you
>> in the error message to use `= x` instead of `= [x]`, since
>> it’s a common pattern in C. My best bet is that no-one uses
>> `[0]` being in fact `[0, 0xFF …]` intentionally.
>
> Only because of the insane idea of intentionally invalid
> initialization
>
> `int[N]=[1,2,3]` being trailing zeros makes more sense
D not copying that C behavior is sane. But what makes it bad is
that D still allows you to not define all elements of the array,
and implicitly initiliszes them in a non intuative way.
Here is what I'd change it to:
```
float[10] a = [42]; // This should be a error.
float[10] b = [0:42, 5: 3.14]; // This also should be an error.
float[10] c = [0..$: 0]; // Sets all to zero.
float[10] d = [42, 1..$: 0]; // First element is 42, everything
else is zero.
float[10] e = [1..$: 42]; // Error, first element is not defined.
```
This should be familiar due to the slicing syntax D already has.
More information about the Digitalmars-d
mailing list