The case for NaN

Walter Bright newshound2 at digitalmars.com
Sun Jul 5 08:11:31 UTC 2026


On 7/4/2026 5:29 PM, H. S. Teoh wrote:
> On Sat, Jul 04, 2026 at 04:55:22PM -0700, Walter Bright via Digitalmars-d wrote:
>> Of course. The issue is really that floating point is the best we can
>> do when attempting to represent irrational numbers. We cannot even
>> represent them on paper, other than as symbols like pi.
> 
> Mostly, but not 100% true.
> [...]

I didn't know that! Nice read. Thank you for posting it.


>> The bottom line is default 0.0 initialization hides bugs, and NaN
>> exposes bugs. I prefer the latter.
> 
> Your argument only applies to *modifying* existing *C* code that fails
> to initialize float variables and assuming 0.0 is valid initialization.
> 
> For new code, written in D which initializes by default, your argument
> doesn't apply.  New code is written to work with whatever default value
> the language imposes on the type, so whether it's NaN or 0.0 doesn't
> actually change anything.

It still applies. People will still write:
```d
float f;
```
and forget to initialize it. If it defaults to 0, and 0 is not correct for the 
need, then a subtle bug is introduced.

If it defaults to NaN, it will (eventually) force the programmer to think about 
what the actual initial value should be. That is the goal of this.


> For code ported from C, yes defaulting to NaN will catch bugs.  But if
> you're porting from C, you shouldn't be copy-n-pasting code blindly
> without review to begin with.

When you're converting boatloads of C to D, reviewing every line is not going to 
happen. What people should do and what they actually do can be very different. D 
is designed, as I pointed out earlier, to make it easier to do the right thing 
than the wrong thing.


> Code that performs integer calculation also suffers from the same
> problem if you fail to initial your integer to the right value, and got
> 0 instead.

I would have used int.NaN if there was a NaN value for integers.


> You might as well say we should initialize ints to -INTMAX
> so that if your result suddenly comes out as an unusually large number
> where you expect a small one, you'll know if you have a bug.

Indeed, with int.min you may notice something is wrong, but with NaN you are 
going to notice something is wrong.


More information about the Digitalmars-d mailing list