Table of Contents

<fenv.h>

<fenv.h> provides access to the floating-point environment: exception flags that record invalid operations, overflows, and underflows, plus rounding mode control. Essential for checking whether computations silently produced NaN or infinity.

Use it to detect floating-point anomalies and test numerical edge cases portably.

Example

This example checks which floating-point exception flags are set after various computations.

// compile: gcc -o fenvexample fenvexample.c -lm
// run: ./fenvexample
// description: detect floating-point exceptions (invalid, overflow, etc.)
 
#include <fenv.h>
#include <math.h>
#include <stdio.h>
 
int main() {
    volatile double x;
 
    feclearexcept(FE_ALL_EXCEPT);
    x = sqrt(-1.0);
    if (fetestexcept(FE_INVALID))
        printf("sqrt(-1.0) set FE_INVALID\n");
 
    feclearexcept(FE_ALL_EXCEPT);
    x = 1.0 / 0.0;
    if (fetestexcept(FE_DIVBYZERO))
        printf("1.0/0.0 set FE_DIVBYZERO\n");
 
    feclearexcept(FE_ALL_EXCEPT);
    x = 1e308 * 1e308;
    if (fetestexcept(FE_OVERFLOW))
        printf("1e308*1e308 set FE_OVERFLOW\n");
 
    return 0;
}