floats default to NaN... why?

Jonathan M Davis jmdavisProg at gmx.com
Fri Apr 13 22:58:00 PDT 2012


On Saturday, April 14, 2012 07:41:33 F i L wrote:
> > You're supposed to initialize them or assign them
> > to appropriate values before using them.
> 
> sure, but if they always default to _usable_ constants no
> expectations are lost and no bugs are created.

No. You always have a bug if you don't initialize a variable to the value that 
it's supposed to be. It doesn't matter whether it's 0, NaN, 527.1209823, or 
whatever. All having a default value that you're more likely to use means is 
that you're less likely to have to explicitly initialize the variable. It has 
to be initialized to the correct value regardless. And if you're in the habit 
of always initializing variables and never relying on the defaults if you can 
help it, then the cases where variables weren't initialized to what they were 
supposed to be stand out more.

> > but the whole purpose of default initialization is to make code
> > fail
> > deterministically when variables aren't properly initialized -
> > and to fail as
> > quickly as possible.
> 
> that only makes sense in C/C++ where value are implicitly garbage
> and mess things up.

??? D was designed with an eye to improve on C/C++. In C/C++, variables aren't 
guaranteed to be initialized, so if you forget to initialize them, you get 
garbage, which is not only buggy, it results in non-deterministic behavior. 
It's always a bug to not initialize a variable. D's approach is to say that 
it's _still_ a bug to not initialize a variable, since you almost always need 
to initialize a variable to something _other_ than a default. But rather than 
leaving them as garbage, D makes it so that variables are default-initialized, 
making the buggy behavior deterministic. And since not initializing a variable 
is almost always a bug, default values which were the closest to error values 
for each type were chosen.

You can disagree with the logic, but there it is. I don't see how it's an 
issue, since you almost always need to initialize variables to something other 
than the default, and so leaving them as the default is almost always a bug.

The only point of dispute that I see in general is whether it's better to rely 
on the default or to still explicitly initialize it when you actually want the 
default. Relying on the default works, but by always explicitly initializing 
variables, those which are supposed to be initialized to something other than 
the defaults but aren't are then much more obvious.

Regardless, the _entire_ reason for default-initialization in D revolves 
around making buggy initializations deterministic and more detectable.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list