<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.
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; }
Exception flags (bit flags for fetestexcept, feclearexcept):
FE_INEXACT: result not representableFE_UNDERFLOW: underflow to zero or subnormalFE_OVERFLOW: result too large to representFE_DIVBYZERO: division by zeroFE_INVALID: invalid operation (sqrt(-1), NaN comparison)FE_ALL_EXCEPT: all exception flagsException handling:
feclearexcept(excepts): clear specified flagsfetestexcept(excepts): test which flags are setfegetexceptflag(&state, excepts): save flags to variablefesetexceptflag(&state, excepts): restore flags from variableRounding modes:
FE_DOWNWARD, FE_TONEAREST, FE_TOWARDZERO, FE_UPWARDfegetround(): query current rounding modefesetround(mode): set rounding modeEnvironment save/restore:
fegetenv(&env): save full FP environmentfesetenv(&env): restore FP environmentfeupdateenv(&env): restore and re-raise current exceptions