float init 0 request

Mike Shah mshah.475 at gmail.com
Tue Aug 18 02:53:56 UTC 2026


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.

It's helped me more than a handful of times when building a 
linear algebra math library to always explicitly initialize 
floating point values and never assume zero.

I like NaN because the error propogates, it's very easy to detect 
and then debug NaN versus a garbage value which can sneak by.

floating point numbers being initialized to NaN is a good 
reminder that while they're 'grouped' and often taught as 'a 
primitive type' -- they behave differently (i.e. drift error, 
can't represent everything, need to be compared carefully, etc.)!


More information about the Digitalmars-d mailing list