Movement against float.init being nan

Walter Bright newshound2 at digitalmars.com
Sun Aug 21 16:51:51 UTC 2022


Consider the following pattern, which doesn't appear frequently, but frequently 
enough:

     double x;
     if (condition) {
         x = 5;
         ...
     }
     ...               // (1)
     if (condition) {
        foo(x);
     }

Imagine there's a lot more code omitted which obscures the pattern. This code is 
correct.

Now, maintainer adds `bar(x)` at (1).

The scenarios:

1. x is default initialized to NaN. bar(x) produces a NaN result on everything 
dependent on x. User knows there's a problem.

2. x is default initialized to 0. bar(0) may exhibit problems, but these 
problems won't necessarily be noticed.

3. compiler complains that `double x;` needs an initializer. To shut up the 
compiler, the user initializes it to 0, without putting much thought into it. 
bar(0) may exhibit problems, but these won't necessarily be noticed.

4. compiler complains that `double x;` needs an initializer. Coder just schlepps 
in a 0. Yes, this happens. Maintainer wastes time wondering why x is initialized 
to 0, as that may be a nonsense value for x. Maintainer wonders if this unused 
initialization has a purpose, maybe it is the result of a bad refactoring? 
Wastes more time investigating it.

D chose option 1.

BTW, option 1 is very analogous to the common "Optional" types which can be 
either an error value or a valid value. Optional types propagate just like NaNs do.


More information about the Digitalmars-d mailing list