Updated: 2008-08-11

Index Return to Main Contents

#include <math.h>#include <errno.h>#include <fenv.h>

A portable program that needs to check for an error from a mathematical
function should set
*errno*
to zero, and make the following call

feclearexcept(FE_ALL_EXCEPT);before calling a mathematical function.

Upon return from the mathematical function, if
*errno*
is nonzero, or the following call (see
**fenv**(3))
returns nonzero

fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW);then an error occurred in the mathematical function.

The error conditions that can occur for mathematical functions are described below.

A floating result
*overflows*
if the result is finite,
but is too large to represented in the result type.
When an overflow occurs,
the function returns the value
**HUGE_VAL**,
**HUGE_VALF**,
or
**HUGE_VALL**,
depending on whether the function result type is
*double*,
*float*,
or
*long double*.
*errno*
is set to
**ERANGE**,
and an "overflow"
(**FE_OVERFLOW**)
floating-point exception is raised.

A floating result
*underflows*
if the result is too small to be represented in the result type.
If an underflow occurs,
a mathematical function typically returns 0.0
(C99 says a function shall return "an implementation-defined value
whose magnitude is no greater than the smallest normalized
positive number in the specified type").
*errno*
may be set to
**ERANGE**,
and an "overflow"
(**FE_UNDERFLOW**)
floating-point exception may be raised.

Some functions deliver a range error if the supplied argument value,
or the correct function result, would be
*subnormal*.
A subnormal value is one that is nonzero,
but with a magnitude that is so small that
it can't be presented in normalized form
(i.e., with a 1 in the most significant bit of the significand).
The representation of a subnormal number will contain one
or more leading zeros in the significand.

To avoid the complexities of using
*errno*
and
**fetestexcept**(3)
for error checking,
it is often advised that one should instead check for bad argument
values before each call.
For example, the following code ensures that
**log**(3)'s
argument is not a NaN and is not zero (a pole error) or
less than zero (a domain error):

double x, r; if (isnan(x) || islessequal(x, 0)) { /* Deal with NaN / pole error / domain error */ } r = log(x);The discussion on this page does not apply to the complex mathematical functions (i.e., those declared by

The
**gcc**(1)
*-fno-math-errno*
option causes the executable to employ implementations of some
mathematical functions that are faster than the standard
implementations, but do not set
*errno*
on error.
(The
**gcc**(1)
*-ffast-math*
option also enables
*-fno-math-errno*.)
An error can still be tested for using
**fetestexcept**(3).