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
Be careful with NaN's... they can spread like wildfire if you are not careful.
They are a perfectly valid value for floats, but any assignments involving them will also equal NaN, so they propagate through your code. This is quite good as a debugging tool if you catch it, however it can also be a real nuisance if you are bringing something to release and there is a fringe case somewhere.
D uses this as rationale for giving floats NaN as default. (Which I'm not sure I agree with.)
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]
My feelings are that it's a bit hacky, but at least every other numbers you make operations with this NaN value gives NaN as result - when you see a NaN in a bug report, at least you know what kind of mistake you are hunting.