aka*_*tar 2 c++ floating-point performance
我希望能够做到以下几点:
float func()
{
if( error ) return InvalidFloatingPointValue;
else return 0.0f;
}
// somewhere else
float a = func();
if( a == InvalidFloatingPointValue )
DoSomething();
Run Code Online (Sandbox Code Playgroud)
我有什么理由不这样做吗?是否存在可以快速安全地用于此类测试的交叉编译器,跨平台(Windows,Linux,Android)值?
你可以退回NaN.这依赖于在某些时候检查其他表达式中使用return的返回或结果,因此应该记录.
#include <limits> // std::numeric_linits
float func()
{
return error ? std::numeric_limits<float>::quiet_NaN() : 0.0f;
}
Run Code Online (Sandbox Code Playgroud)
使用C++ 11,您可以使用检查返回的值是否为NaN std::isnan.但是你不应该将NaN与平等进行比较:它们的比较总是产生false.有利的一面是,a != a是true,如果a是NaN.
#include <cmath> // std::isnan, requires C++11
float a = func();
if(std::isnan(a)) DoSomething();
Run Code Online (Sandbox Code Playgroud)