Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

<fenv.h> — floating-point environment

The <fenv.h> header exposes floating-point exception flags and control modes. It lets programs inspect exceptional conditions, change rounding, and save and restore a thread’s environment.

Version: C23; repository compiler flag, production runtime not attested

Syntax

#include <fenv.h>
#pragma STDC FENV_ACCESS ON

<fenv.h> manages status flags and control modes. fenv_t represents the entire dynamic environment, fexcept_t exception status, and femode_t control modes alone. The dynamic environment is thread-local.

FE_DIVBYZERO means division by zero, FE_INVALID invalid operation, FE_OVERFLOW overflow, FE_UNDERFLOW underflow, and FE_INEXACT an inexact result. Ordinary arithmetic does not clear exception flags that are already set. Restoring a saved environment with fesetenv can, however, clear flags that were not set in the saved state, without a separate call to feclearexcept. FE_ALL_EXCEPT combines all supported exceptions with |; it is 0 if none exist. Use feclearexcept and fetestexcept.

FE_DOWNWARD rounds toward −∞, FE_UPWARD toward +∞, FE_TOWARDZERO toward zero, FE_TONEAREST to the nearest value, and FE_TONEARESTFROMZERO to the nearest value with ties away from zero. For FE_TONEAREST, ties-to-even is guaranteed under the IEC 60559 bindings in Annex F. The presence of the macro alone does not guarantee this tie-breaking rule. Individual exception and direction macros exist only with corresponding support; check #ifdef. fegetround reads the dynamic direction; fesetround sets it.

FE_DFL_ENV designates the default environment for fesetenv; FE_DFL_MODE designates default modes for fesetmode, without restoring flags. FE_DYNAMIC is a token for #pragma STDC FENV_ROUND FE_DYNAMIC, selecting dynamic rounding, not a fesetround argument.

Use #pragma STDC FENV_ACCESS ON when testing flags or using non-default dynamic modes. Check operation results and restore saved state. A repository compiler’s C23 selection alone does not attest production-runtime support.

Examples

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

#pragma STDC FENV_ACCESS ON

int main(void)
{
    fenv_t saved;
    int cleared;

    if (fegetenv(&saved) != 0)
        return EXIT_FAILURE;

    if (feclearexcept(FE_ALL_EXCEPT) != 0) {
        (void)fesetenv(&saved);
        return EXIT_FAILURE;
    }

    cleared = fetestexcept(FE_ALL_EXCEPT) == 0;
    if (fesetenv(&saved) != 0)
        return EXIT_FAILURE;

    puts(cleared ? "flags clear" : "unexpected flags");
    return cleared ? EXIT_SUCCESS : EXIT_FAILURE;
}

Result

flags clear

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources