Remix.run Logo
WalterBright 3 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.
ncurses1010 an hour ago | parent [-]

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?

WalterBright 37 minutes ago | parent [-]

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.