Floating point types default to NaN?

Jonathan M Davis newsgroup.d at jmdavisprog.com
Fri Nov 24 22:38:49 UTC 2017


On Friday, November 24, 2017 20:43:14 A Guy With a Question via Digitalmars-
d-learn wrote:
> On Friday, 24 November 2017 at 14:43:24 UTC, Adam D. Ruppe wrote:
> > On Friday, 24 November 2017 at 14:30:44 UTC, A Guy With a
> >
> > Question wrote:
> >> I would have expected 0 to be the default value. What's the
> >> logic behind having them being NaN by default?
> >
> > It gives you a runtime error (sort of) if you use an
> > uninitialized variable.
> >
> > You ARE supposed to explicitly initialize variables to your own
> > values in D. The automatic init is to make errors stand out
> > more consistently if you don't do this as opposed to being
> > random.
> >
> > So pointers are initialized to null - an invalid value that
> > stands out if you try to use it. chars get \xFF - again,
> > invalid that will throw if you try to utf decode it. Floats get
> > NaN which is as close to invalid as they get.
> >
> > ints happen to get 0 not to be convenient, but because there is
> > no clearly-invalid int value so something had to be chosen, and
> > 0 was just easy to implement....
>
> If thats the case why not just throw a compiler error? D has a
> way explicitly not set it right? Through void...So if the intent
> is to find erroneous code right away, just throw a compiler error
> no?

That requires data flow analysis, which the compiler doesn't do a lot of,
because it can be complicated. It also tends to result in the compiler
giving warnings or errors in cases where it's not actually true that the
variable is used before it's given a value, because it can't do it
perfectly. There was a recent discussion on this in the main newsgroup with
regards to guaranteeing with a pointer or reference was initialized to
something other than null.

Also, when you start having stuff like arrays, having a default initializer
is a big boon, since then all of the elements have a default value. It's
going to work even worse to try and have the compiler detect when you've
properly initialized every element in an array than have it detect when
you've properly initialized just a variable. And stuff like the out
attribute relies on there being a default initializer. Just all around,
having default initializers for types in general makes things cleaner and
less error-prone.

And NaN math is something that's built into CPU. Operations other than
default initialization can result in a floating point value being NaN. So,
if you're looking to have NaN not be a thing for floating point values, then
you're out of luck. And Walter is a big fan of NaN being a thing, since when
you hit it, you know that you've found a bug, and tracking it down tends to
be fairly straightforward, which is not the case with many other types of
bugs.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list