Floating point types default to NaN?

Adam D. Ruppe destructionator at gmail.com
Fri Nov 24 14:43:24 UTC 2017


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....


More information about the Digitalmars-d-learn mailing list