feclearexcept - Linux
Overview
feclearexcept clears the floating-point exceptions flags: FE_ALL_EXCEPT
(or FE_INVALID
, FE_DIVBYZERO
, FE_OVERFLOW
and FE_UNDERFLOW
). It is commonly used to reset the flags before performing floating-point calculations to ensure a clean slate.
Syntax
feclearexcept(int excepts)
Options/Flags
The excepts parameter is a bitmask of the exceptions to clear. It can be any combination of the following values:
FE_INVALID
(1): Invalid operation exceptionFE_DIVBYZERO
(2): Division by zero exceptionFE_OVERFLOW
(4): Overflow exceptionFE_UNDERFLOW
(8): Underflow exceptionFE_ALL_EXCEPT
(15): All of the above exceptions
Examples
Clear all exceptions:
#include <fenv.h>
int main() {
feclearexcept(FE_ALL_EXCEPT);
return 0;
}
Clear only the division by zero exception:
#include <fenv.h>
int main() {
feclearexcept(FE_DIVBYZERO);
return 0;
}
Common Issues
Error handling: If feclearexcept fails to clear the exceptions, it sets the FE_INVALID
exception and returns -1
. Check the return value to ensure successful clearing of exceptions.
Integration
Using feclearexcept with floating-point precision:
#include <fenv.h>
#include <math.h>
int main() {
float x = 1e20;
float y = 1e-20;
feclearexcept(FE_ALL_EXCEPT);
float result = x * y;
if (fetestexcept(FE_UNDERFLOW)) {
printf("Underflow occurred during calculation.\n");
}
return 0;
}
Related Commands
fegetexcept
: Get the floating-point exceptions flags.fesetexcept
: Set the floating-point exceptions flags.raise
: Raise a floating-point exception.