C fenv.h Header

Beginner
6 min read
Updated: Nov 2026
3 examples
C99

What Is fenv.h?

<fenv.h> is the C99 header for the floating-point environment: the status flags that record exceptions such as divide-by-zero, overflow, and inexact results, and the current rounding mode.

Use it to detect whether a computation raised an exception without crashing, and to switch between rounding to nearest, up, down, or toward zero. The settings apply to the calling thread.

Remember
#include <fenv.h>

feclearexcept(FE_ALL_EXCEPT);   /* clear flags */
... floating-point work ...
fetestexcept(FE_DIVBYZERO);     /* nonzero if flag set */

fegetround()            -> current rounding mode
fesetround(FE_UPWARD)   -> 0 on success

link with -lm on GCC and Clang
UsePrefer
Detect divide by zero or overflowfetestexcept()
Reset flags before a computationfeclearexcept()
Change rounding directionfesetround()
Save and restore everythingfegetenv() / fesetenv()

How to Use fenv.h in C

Clear the flags, run the floating-point work, then test the flags you care about.

  1. Add #include <fenv.h>.
  2. Call feclearexcept(FE_ALL_EXCEPT) before the code you want to inspect.
  3. Run the floating-point operations. Use volatile or runtime values so the compiler does not fold them away.
  4. Test flags with fetestexcept(mask); the result is nonzero when any flag in the mask is set.
  5. If you change the rounding mode, save fegetround() first and restore it afterwards.
PieceRequired?Role
#include <fenv.h>YesDeclares the functions and FE_* macros
#pragma STDC FENV_ACCESS ONRecommendedTells the compiler you read flags or change modes (some compilers, such as GCC, ignore it)
-lmUsuallyLinks the math library on GCC and Clang

Pseudocode

Pseudocode
feclearexcept(FE_ALL_EXCEPT)
result = compute()
if fetestexcept(FE_DIVBYZERO | FE_OVERFLOW):
    report problem

saved = fegetround()
fesetround(FE_DOWNWARD)
...
fesetround(saved)

Cheat Sheet

Exception and rounding macros are defined only when the platform supports them.

NameMeaning
FE_DIVBYZERODivision by zero flag
FE_INEXACTThe result had to be rounded
FE_INVALIDInvalid operation such as 0.0 / 0.0
FE_OVERFLOWResult too large to represent
FE_UNDERFLOWResult too small to represent
FE_ALL_EXCEPTBitwise OR of every supported exception flag
FE_TONEAREST, FE_UPWARD, FE_DOWNWARD, FE_TOWARDZERORounding modes
feclearexcept, fetestexcept, feraiseexceptClear, test, and raise flags
fegetround, fesetroundRead and set the rounding direction
fegetenv, fesetenv, feholdexcept, feupdateenvSave and restore the whole environment

Worked Walkthrough — Flags and Rounding

See how a division sets a flag and how rint(2.5) changes with the rounding mode.

Calculation
feclearexcept(FE_ALL_EXCEPT)   -> all flags off
x = 1.0 / 0.0                  -> result +inf, FE_DIVBYZERO set
fetestexcept(FE_DIVBYZERO)     -> nonzero

rint(2.5) under each rounding mode:
FE_TONEAREST   -> 2   (ties go to even)
FE_UPWARD      -> 3
FE_DOWNWARD    -> 2
FE_TOWARDZERO  -> 2

C Examples

Compile with gcc file.c -std=c11 -o out (add -lm at the end).

Example 1 — Detect a Divide by Zero

Divide by zero in floating point, then check the flag instead of crashing.

C
#include <fenv.h>
#include <math.h>
#include <stdio.h>

#pragma STDC FENV_ACCESS ON

int main(void) {
    volatile double zero = 0.0;
    volatile double result;

    feclearexcept(FE_ALL_EXCEPT);
    result = 1.0 / zero;

    if (fetestexcept(FE_DIVBYZERO)) {
        printf("divide by zero flagged\n");
    }
    printf("result is infinite: %s\n", isinf(result) ? "yes" : "no");
    return 0;
}

How It Works

  1. Clear first. feclearexcept(FE_ALL_EXCEPT) removes old flags.
  2. Prevent folding. volatile forces the division to happen at run time.
  3. Floating-point does not trap. 1.0 / 0.0 produces infinity and sets FE_DIVBYZERO.
  4. Test the flag. fetestexcept returns nonzero, and isinf confirms the result.

Example 2 — Compare Rounding Modes

Round the same value with rint() under each rounding direction.

C
#include <fenv.h>
#include <math.h>
#include <stdio.h>

struct Mode {
    int mode;
    const char *name;
};

int main(void) {
    volatile double x = 2.5;
    const struct Mode modes[] = {
        { FE_TONEAREST,  "to nearest" },
        { FE_UPWARD,     "upward" },
        { FE_DOWNWARD,   "downward" },
        { FE_TOWARDZERO, "toward zero" }
    };
    int saved = fegetround();
    size_t i;

    for (i = 0; i < sizeof modes / sizeof modes[0]; i++) {
        if (fesetround(modes[i].mode) == 0) {
            printf("%s: %.0f\n", modes[i].name, rint(x));
        }
    }

    fesetround(saved);
    return 0;
}

How It Works

  1. Save the mode. fegetround() remembers the original direction.
  2. Switch modes. fesetround returns 0 when the mode is supported.
  3. Round with rint(). rint honors the current mode. Ties go to the even value, so 2.5 becomes 2 to nearest.
  4. Restore. The last fesetround(saved) returns the program to normal.

Example 3 — Detect an Inexact Result

Compare an exact calculation with one that must be rounded.

C
#include <fenv.h>
#include <stdio.h>

int main(void) {
    volatile double one = 1.0;
    volatile double three = 3.0;
    volatile double half = 0.5;
    volatile double quarter = 0.25;
    volatile double r;

    feclearexcept(FE_ALL_EXCEPT);
    r = one / three;
    printf("1 / 3 inexact: %s\n", fetestexcept(FE_INEXACT) ? "yes" : "no");

    feclearexcept(FE_ALL_EXCEPT);
    r = half + quarter;
    printf("0.5 + 0.25 inexact: %s\n", fetestexcept(FE_INEXACT) ? "yes" : "no");

    (void)r;
    return 0;
}

How It Works

  1. Clear before each test. Flags stay set until you clear them.
  2. 1/3 cannot be exact. The binary result is rounded, so FE_INEXACT is raised.
  3. 0.5 + 0.25 is exact. Both values are powers of two, so 0.75 is represented exactly.

Edge Cases & Pitfalls

Floating-point flags are easy to misread when the compiler optimizes aggressively.

pragma

Tell the compiler you read flags

Without #pragma STDC FENV_ACCESS ON (or an option such as -frounding-math on GCC) the compiler may reorder or fold operations across your flag tests.

const

Constant folding hides flags

1.0 / 0.0 written with literals can be folded at compile time, so the flag never sets at run time. Use volatile operands in demos.

restore

Restore the rounding mode

Save fegetround() and restore it before calling code that expects round-to-nearest.

optional

Macros are optional

FE_UPWARD and similar macros exist only when the hardware supports them, and fesetround returns nonzero for an unsupported mode.

Performance & Portability Notes

ApproachCostBest for
fetestexcept / feclearexceptRead or clear status flags; cheapChecking a block of math
fesetroundSlower than ordinary arithmetic on many CPUsOccasional mode switches
Switching per iterationCan dominate the loop costAvoid in hot loops

Integer division by zero is different: it is undefined behavior and often crashes. Floating-point division by zero is defined by IEEE 754 and only sets a flag.

Key Takeaways

  • Role: inspect floating-point exception flags and control rounding.
  • Flow: feclearexcept, run the math, then fetestexcept.
  • Compiler: use volatile operands or FENV_ACCESS so operations are not folded away.
  • Restore: put the rounding mode back with fesetround when you are done.

One line: fenv.h lets you ask “did that calculation overflow, underflow, or round?” and choose how results are rounded.

Frequently Asked Questions

fenv.h is the C99 header for the floating-point environment: exception status flags and the rounding mode.
Call feclearexcept(FE_ALL_EXCEPT), perform the division, then test fetestexcept(FE_DIVBYZERO).
No. IEEE 754 floating-point division by zero produces infinity and sets FE_DIVBYZERO. Integer division by zero is undefined and may crash.
FE_TONEAREST, FE_UPWARD, FE_DOWNWARD, and FE_TOWARDZERO, when the platform supports them. Use fesetround() to select one.
On GCC and Clang with glibc the fenv functions live in libm, so add -lm at the end of the link line.
It is standard, but not every compiler honors it. GCC ignores it, so use volatile operands or optimization flags such as -frounding-math.

Next: float.h

Inspect floating-point limits such as FLT_MAX and DBL_EPSILON.

float.h tutorial →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful