Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

The following noncompliant code determines the square root of x.

Code Block
bgColor#FFcccc
langc
double x;
double result;

result = sqrt(x);

...

Since this function has domain errors but no range errors, one can use bounds checking to prevent domain errors.

Code Block
bgColor#ccccff
langc
double x;
double result;

if (isless(x, 0)) {
  /* handle domain error */
}

result = sqrt(x);

...

This noncompliant code example determines the hyperbolic cosine of x.

Code Block
bgColor#FFcccc
langc
double x;
double result;

result = cosh(x);

...

Since this function has no domain errors but may have range errors, one must detect a range error and act accordingly.

Code Block
bgColor#ccccff
langc
#include <math.h>
#if defined(math_errhandling) \
  && (math_errhandling & MATH_ERREXCEPT)
#include <fenv.h>
#endif

/* ... */

#if defined(math_errhandling) \
  && (math_errhandling & MATH_ERREXCEPT)
  feclearexcept(FE_ALL_EXCEPT);
#endif
errno = 0;

double x;
double result;

result = sinh(x);

#if !defined(math_errhandling) \
  || (math_errhandling & MATH_ERRNO)
if (errno != 0) {
  /* handle range error */
}
#endif
#if defined(math_errhandling) \
  && (math_errhandling & MATH_ERREXCEPT)
if (fetestexcept(FE_INVALID
               | FE_DIVBYZERO
               | FE_OVERFLOW
               | FE_UNDERFLOW) != 0)
{
  /* handle range error */
}
#endif

...

The following noncompliant code raises x to the power of y.

Code Block
bgColor#FFcccc
langc
double x;
double y;
double result;

result = pow(x, y);

...

Since the pow() function can produce both domain errors and range errors, we must first check that x and y lie within the proper domain. We must also detect if a range error occurs, and act accordingly.

Code Block
bgColor#ccccff
langc
#include <math.h>
#if defined(math_errhandling) \
  && (math_errhandling & MATH_ERREXCEPT)
#include <fenv.h>
#endif

/* ... */

#if defined(math_errhandling) \
  && (math_errhandling & MATH_ERREXCEPT)
  feclearexcept(FE_ALL_EXCEPT);
#endif
errno = 0;

/* call the function */

double x;
double y;
double result;

if (((x == 0.f) && islessequal(y, 0)) || (isless(x, 0))) {
  /* handle domain error */
}

result = pow(x, y);

#if !defined(math_errhandling) \
  || (math_errhandling & MATH_ERRNO)
if (errno != 0) {
  /* handle range error */
}
#endif
#if defined(math_errhandling) \
  && (math_errhandling & MATH_ERREXCEPT)
if (fetestexcept(FE_INVALID
               | FE_DIVBYZERO
               | FE_OVERFLOW
               | FE_UNDERFLOW) != 0)
{
  /* handle range error */
}
#endif

...