float init 0 request

GB gb542 at gmail.com
Wed Aug 26 02:40:54 UTC 2026


On Tuesday, 25 August 2026 at 16:33:01 UTC, Basile B. wrote:
> On Friday, 14 August 2026 at 06:38:02 UTC, Walter Bright wrote:
>> Floats are default initialized to NaN so people will be 
>> coerced to explicitly code what they want the initialized 
>> value to be.
>>
>> I've seen enough code where the programmer forgot to 
>> initialize a float, it was defaulted to 0, and the wrong 
>> result was not detected.
>>
>> ```d
>> float f;     // code reviewer: did the programmer intend it to 
>> be 0?
>> float g = 0; // code reviewer: yes, the programmer likely 
>> meant to initialize it to 0
>> ```
>>
>> It's similar to pointers being default initialized to null. 
>> Trying to use a null pointer will result in a seg fault.
>>
>> Most people decry this, but it's actually a great feature. If 
>> there's a bug in the code, it's better to find it sooner 
>> rather than after you ship.
>
> I have followed the topic since the beginning and I see 
> something that's never been noted: an inconsistency is boolean 
> evaluation.
>
> ```d
> void main()
> {
>     int a;
>     assert(!a); // ok
>     float b;
>     assert(!b); // fails
> }
> ```

Yes, this just exposes a tension in the design:

Goal A - make NaN a good 'uninitialized' poison value.
Goal B - preserve intuitive boolean conversion (e.g. 0 is false, 
nonzero is true).

D seems to prioritize the first goal, at the cost of the 
surprising result that an uninitialized int evaluates as false 
while an uninitialized float (NaN) evaluates as true.

Perhaps something like this could resolve that tension:

@mustAssign float b;
assert(!b);       // compile-time error: b hasn't been assigned

That would let the compiler catch accidental use of an 
uninitialized variable, rather than relying on NaN as a runtime 
sentinel. NaN could then remain useful for what it is actually 
intended to represent: an invalid floating-point result.



More information about the Digitalmars-d mailing list