← Back to context

Comment by WalterBright

15 hours ago

That suggestion is often made.

The trouble with it is a bug I've seen often. People will get an error message about an "uninitialized variable". Then they go into "just get the compiler to shut up" mode, amd pick "0" as the initializer. Then, the program compiles and runs, and silently produces the wrong answer. Code reviews will simply pass over the "0" initializer, as it looks right.

With default NaN initialization, the programmer is more likely to stop and think about it, not just insert 0.

Another issue with it is:

    float x = 0.0;
    setFloat(&x);

    void setFloat(float* px) { *px = 3.0; }

For the purposes of code clarity I don't want to see a variable initialized to a value that is never used, just to shut the compiler up.

With the default initialization to nan, do you ever run into situations where people are searching for common sources for nan (nan literals, div by zero) and they can't find it? Or cases where only some branches but not others initialize the float?

  • To leave a variable uninitialized, use the construction:

        int x = void;
    

    Note that nobody is going to write this by accident. And it's easy to grep for.

    To find the source of a NaN, it helps to know that every operation that has a NaN as an operand produces a NaN as a result. So if you see a NaN in the output, you can work backwards to where it originated.

    • > every operation that has a NaN as an operand produces a NaN as a result.

      That's not true. The minimum/maximum functions (fmin and fminimum_num variants, but not the fminimum one) treat NaN inputs as not-present, so return the non-NaN value if there is one. Similarly, hypot also treats NaN inputs as not-present. pow and compoundn will ignore NaN exponents if the base is 1.

      1 reply →

    • What do you think of kotlins approach where it has a 'todo' function that can always coerce to a type, but instead of populating the variable with a default value that's valid, it just throws