Rule A0-4-4 (required, implementation, partially automated)

Range, domain and pole errors shall be checked when using math functions.

Rationale

The C Standard defines the following types of error related to math functions specifically: domain error – input arguments are outside a domain of a mathematical function definition pole error – for finite input arguments a function gives an exact infinite result

range error – a result of a mathematical function cannot be represented by the return type limitations Domain and pole errors require that bounds are checked for input parameters before calling a mathematical function. Range errors in most cases cannot be prevented, as their occurrence mostly depend on the implementation of floating-point numbers (see A0-4-1). Checking for range errors for multi-threaded applications require that floating-point exception state is in a per-thread basis.

Example

//% $Id: A0-4-4.cpp 305588 2018-01-29 11:07:35Z michal.szczepankiewicz $

#include <cmath>
#include <cfenv>

float Foo(float val)
{
//non-compliant, domain error for negative values
return std::sqrt(val);
}

float Bar(float val)
{
//non-compliant
//domain error for val < 0
//pole error for val==0
return std::log(val);
}

// \return true, if a range error occurred
bool DetectRangeErr()
{
return ((math_errhandling & MATH_ERREXCEPT) &&
(fetestexcept(FE_INEXACT | FE_OVERFLOW | FE_UNDERFLOW) != 0));
}

See also

SEI CERT C++ Coding Standard [10]: FLP32-C: Prevent or detect domain and range errors in math functions