Is it a good idea to use IEEE754 floating point NaN for values which are not set?

后端 未结 9 554
粉色の甜心
粉色の甜心 2020-12-18 22:17

Is it a good idea to use IEEE754 floating point NaN (not-a-number) for values which are undefined for non-mathematical reasons?

In our case they are not yet set beca

9条回答
  •  温柔的废话
    2020-12-18 22:57

    NaNs are a reasonable choice for a 'no value' sentential (the D programming language uses them for uninitialized values, for instance), but because any comparisons involving them will be false, you can get a few surprises:

    • if (result == DEFAULT_VALUE), won't work as expected if DEFAULT_VALUE is NaN, as Jon mentioned.

    • They can also cause problems with range checking if you're not careful. Consider the function:

    bool isOutsideRange(double x, double minValue, double maxValue)
    {
        return x < minValue || x > maxValue;
    }
    

    If x is NaN, this function would incorrectly report that x is between minValue and maxValue.

    If you just want a magic value for users to test against, I'd recommend positive or negative infinity instead of NaN, as it doesn't come with the same traps. Use NaN when you want it for its property that any operations on a NaN result in a NaN: it's handy when you don't want to rely on callers checking the value, for example.

    [Edit: I initially managed to type "any comparisons involving them will be true" above, which is not what I meant, and is wrong, they're all false, apart from NaN != NaN, which is true]

提交回复
热议问题