floats default to NaN... why?

bearophile bearophileHUGS at lycos.com
Sat Apr 14 05:23:08 PDT 2012


F i L:

> So basically, it's for debugging?

To avoid bugs it's useful for all variables to be initialized 
before use (maybe with an explicit annotation for the uncommon 
cases where you want to use uninitialized memory, like: 
http://research.swtch.com/sparse ). Having a variable not 
initialized is a common source of bugs.

C# solves this requiring explicit initialization all variables 
before use. Walter doesn't believe that flow analysis is flexible 
enough in a system language like D (or he doesn't want to 
implement it) so he has not used this idea in D.

So D uses a different worse strategy, it initializes the 
variables to something unusable, so if you try to use them, your 
program fails clearly.

The idea of setting the variables to something useful, like 
setting initialized chars to 'a' and floating point values to 0.0 
looks handy, but on the long run it's not an improvement. You 
sometimes don't initialize a char variable because you are fine 
for it to be 'a', and some other times you don't set it just 
because you forget to initialize it. The compiler can't tell 
apart the two cases, and this is may be a bug in your code.

In practice I think having FP variables initialized to NaN has 
not avoided me significant bugs in the last years. On the other 
hand I have ported some C code that uses global floating point 
arrays/variables to D, and I have had to remove some bugs caused 
by the assumption in the C code that those global FP variables 
are initialized to zero, that's false in D.

Another source of troubles is large fixed-sized FP global arrays, 
that inflate the binary a *lot*. You have to remember to 
initialize them to zero explicitly:

double[100_000] foo; // bad, inflates binary.
double[100_000] bar = 0.0; // good.
void main() {}

In D I'd like the solution used by C# + an annotation to not 
initialize a variable or array.

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list