I have double (or float) variables that might be ’empty’, as in holding no valid value. How can I represent this condition with the built in types float and double?
One option would be a wrapper that has a float and a boolean, but that can´t work, as my libraries have containers that store doubles and not objects that behave as doubles. Another would be using NaN (std::numeric_limits). But I see no way to check for a variable being NaN.
How can I solve the problem of needing a ‘special’ float value to mean something other than the number?
In Visual C++, there is a non-standard
_isnan(double)function that you can import throughfloat.h.In C, there is a
isnan(double)function that you can import throughmath.h.In C++, there is a isnan(double) function that you can import through
cmath.As others have pointed out, using NaN’s can be a lot of hassle. They are a special case that has to be dealt with like NULL pointers. The difference is that a NaN will not usually cause core dumps and application failures, but they are extremely hard to track down. If you decide to use NaN’s, use them as little as possible. Overuse of NaN’s is an offensive coding practice.