floats default to NaN... why?

Joseph Rushton Wakeling joseph.wakeling at webdrake.net
Sat Apr 14 12:37:33 PDT 2012


On 14/04/12 16:52, F i L wrote:
>> The initialization values chosen are also determined by the underlying
>> hardware implementation of the type. Signalling NANs
>> (http://en.wikipedia.org/wiki/NaN#Signaling_NaN) can be used with floats
>> because they are implemented by the CPU, but in the case of integers or
>> strings their aren't really equivalent values.
>
> I'm sure the hardware can just as easily signal zeros.

The point is not that the hardware can't deal with floats initialized to zero. 
The point is that the hardware CAN'T support an integer equivalent of NaN.  If 
it did, D would surely use it.

> Like I said before, this is backwards thinking. At the end of the day, you
> _can_ use default values in D. Given that ints are defaulted to usable values,
> FP Values should be as well for the sake of consistency and convenience.

Speaking as a new user (well, -ish), my understanding of D is that its design 
philosophy is that _the easy thing to do should be the safe thing to do_, and 
this concept is pervasive throughout the design of the whole language.

So, ideally (as bearophile says) you'd compel the programmer to explicitly 
initialize variables before using them, or explicitly specify that they are not 
being initialized deliberately.  Enforcing that may be tricky (most likely not 
impossible, but tricky, and there are bigger problems to solve for now), so the 
next best thing is to default-initialize variables to something that will scream 
at you "THIS IS WRONG!!" when the program runs, and so force you to correct the 
error.

For floats, that means NaN.  For ints, the best thing you can do is zero.  It's 
a consistent decision -- not consistent as you frame it, but consistent with the 
language design philosophy.

> You can't force new D programmers to follow a 'guidline' no matter how loudly the documentation shouts it

No, but you can drop very strong hints as to good practice.  Relying on default 
values for variables is bad programming.  The fact that it is possible with 
integers is a design fault forced on the language by hardware constraints.  As a 
language designer, do you compound the fault by making floats also init to 0 or 
do you enforce good practice in a way which will probably make the user 
reconsider any assumptions they may have made for ints?

Novice programmers need support, but support should not extend to pandering to 
bad habits which they would be better off unlearning (or never learning in the 
first place).


More information about the Digitalmars-d-learn mailing list