Movement against float.init being nan

Hipreme msnmancini at hotmail.com
Fri Aug 19 18:57:25 UTC 2022


On Friday, 19 August 2022 at 16:34:59 UTC, 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.

Well, it **is** used as initialization substitute, if wasn't 
meant to be a substitute, not initializing a variable should be a 
compilation error. There's a lot of developers which uses bool 
and int because they make sense, when dealing with floating point 
they forget about that they do not make sense. I've never had any 
problem with float defaulting to 0 on Java. If the error happens, 
I get at max division by 0 exception. NaN does not cause this 
exception which actually makes the bug harder to find.


More information about the Digitalmars-d mailing list