可测试的无效浮点值。 (浮点NULL)

时间:2015-03-22 12:26:01

标签: c++ performance floating-point

我希望能够做到以下几点:

float func()
{
    if( error ) return InvalidFloatingPointValue;
    else return 0.0f;
}

// somewhere else
float a = func();
if( a == InvalidFloatingPointValue )
    DoSomething();

我有什么理由不这样做吗? 是否存在可以快速安全地用于此类测试的交叉编译器,跨平台(Windows,Linux,Android)值?

3 个答案:

答案 0 :(得分:8)

你可以退回NaN。这依赖于在某些时候检查其他表达式中使用return的返回或结果,因此应该记录下来。

#include <limits> // std::numeric_linits

float func()
{
  return  error ? std::numeric_limits<float>::quiet_NaN() : 0.0f;
}

在C ++ 11支持下,您可以使用std::isnan检查返回的值是否为NaN。但是你不应该将NaN比较为平等:它们的比较总是产生false。如果a != a是NaN,那么truea则具有优势。

#include <cmath> // std::isnan, requires C++11

float a = func();
if(std::isnan(a)) DoSomething();

答案 1 :(得分:4)

您可以将NaN用作@juanchopanza suggested,但NaN可以是微妙的(NaN == NaNfalse),也不清楚任何人阅读代码返回的值可能具有无效值。

我认为更适合这个问题的是boost::optional<float>

用法:

boost::optional<float> func()
{
    if (error) 
        return boost::none;
    else
        return 0f;
}

// somewhere else
auto a = func();
if (!a)
    DoSomething();
else {
   // use *a
}

答案 2 :(得分:1)

使用异常可能更好。或者,您可以使用bool返回值类型和float&引用(输出)参数。