Oracle® Solaris Studio 12.4: Numerical Computation Guide

Exit Print View

Updated: January 2015
 
 

4.3.2 C99 Exception Flag Functions

C/C++ programs can test, set, and clear the floating-point exception flags using the C99 floating-point environment functions. The header file fenv.h defines five macros corresponding to the five standard exceptions: FE_INEXACT, FE_UNDERFLOW, FE_OVERFLOW, FE_DIVBYZERO, and FE_INVALID. It also defines the macro FE_ALL_EXCEPT to be the bitwise “or” of all five exception macros. These macros can be combined to test or clear any subset of the exception flags or raise any combination of exceptions. The following examples show the use of these macros with several of the C99 floating-point environment functions. See the feclearexcept(3M) manual page for more information.


Note -  For consistent behavior, do not use both the C99 floating-point environment functions and extensions in libm and the ieee_flags and ieee_handler functions in libsunmath in the same program.

To clear all five exception flags, use the following:

feclearexcept(FE_ALL_EXCEPT);

To test whether the invalid operation or division by zero flags have been raised, use the following:

int i;

i = fetestexcept(FE_INVALID | FE_DIVBYZERO);
if (i & FE_INVALID)
    /* invalid flag was raised */
else if (i & FE_DIVBYZERO)
    /* division-by-zero flag was raised */

The fegetexceptflag and fesetexceptflag functions provide a way to save and restore a subset of the flags. The next example shows one way to use these functions.

fexcept_t flags;
 
/* save the underflow, overflow, and inexact flags */
fegetexceptflag(&flags, FE_UNDERFLOW | FE_OVERFLOW | FE_INEXACT);
/* clear these flags */
feclearexcept(FE_UNDERFLOW | FE_OVERFLOW | FE_INEXACT);
/* do a computation that can underflow or overflow */
...
/* check for underflow or overflow */
if (fetestexcept(FE_UNDERFLOW | FE_OVERFLOW) != 0) {
    ...
}
/* restore the underflow, overflow, and inexact flags */
fesetexceptflag(&flags, FE_UNDERFLOW | FE_OVERFLOW, | FE_INEXACT);