Movement against float.init being nan
Steven Schveighoffer
schveiguy at gmail.com
Fri Aug 19 17:14:35 UTC 2022
On 8/19/22 12:34 PM, Basile B. wrote:
> On Friday, 19 August 2022 at 13:42:58 UTC, Hipreme wrote:
>> As someone coming from Java to use D, I find it myself quite annoying
>> that float and double are initialized to `nan`.
>>
>> This is really bad, it is hard to detect for newcomers, there is no
>> flag by default to throw an exception when some operation on nan is
>> done. It can be misleading if you're not paying a lot of attention to
>> what you're doing.
>>
>> What I suggest is what any sane people would: use 0 as the start for
>> float and double. 0 is the most common sense as a starting point for
>> everything, and, there are 2 options we could go:
>>
>>
>> 1: Emit a compilation error that every variable must be initialized (I
>> thought D were trying to avoid runtime errors)
>> 2: 0 init all types, so, none is actually invalid before use
>>
>>
>> Even `char` took me as surprise to know it actually starts as 0xff, I
>> lost a bit of time trying to find that bug because it is so common
>> that variables init as zero.
>>
>> Although the `char` is a bit different beast in terms of breaking
>> change, I really *can't see* anyone actually depending that your float
>> is being initialized with `nan`, so I really would like to know how
>> much people agree with this idea. It is so common to stumble on that
>> problem that it is starting to feel as a real mistake.
>
> It's not a mistake, default initialization in D is not designed to be an
> initialization substitute, it's designed in a way that missing
> initialization is easily detectable but not UB. However, thruth is that
> this only works for character and floating point types.
>
> Changing that design would require a DIP I think.
This is true, it's not a mistake, it is on purpose. The original idea
behind default values is to correct so many mistakes from C where values
are not initialized but just "happen" to work until it doesn't. But
practically, it is now used as de-facto initialization, it's just too
convenient. In that mindset, floats defaulting to NaN are an outlier.
However, in my recent efforts to port a decently sized C library to D,
one thing I don't have a good answer for is code like:
```c
ReallyLargeStruct foo = { 0 };
```
There just is no equivalent in D. In order to set all fields to 0, I
would have to specify a complete layout of the entire thing. This could
probably be done via introspection. But I just don't like it even in
that case.
The easier thing to do is to default the `float` and `double` fields to
0 in the type definition, and then use default initialization to achieve
the same. So I think in some cases, it's much nicer to just rely on the
default initialization.
I also would prefer that all floats/doubles default to 0 instead of NaN.
-Steve
More information about the Digitalmars-d
mailing list