What is fesetexceptflag() in C?
The fesetexceptflag function is a C library function that resets the floating-point environment’s exception status flags.
To use the fesetexceptflag function, we need to import the fenv.h header file, as shown below:
#include <fenv.h>
Syntax
The fesetexceptflag is declared as follows:
Parameters
-
The first parameter,
flagp, is a pointer to thefexecpt_tobject type from where the flags are read. This object represents the floating-point status flags. -
The second parameter,
excepts, is the bitwise OR of macros’ values that represents the floating-point exception flags. These macros are defined in thefenv.hheader.
Return value
The fesetexceptflag function returns a zero if all the flags are set successfully. It returns a non-zero value otherwise (in case of an error).
Example
The fesetexceptflag resets the flags to a state that the fegetexceptflag function saved.
-
First, we enable the
pragma FENV_ACCESSso that the program can call the functions. -
We set the floating-point exception macros in the
set_execptionsfunction defined in the program. Thefetestexceptfunction sets the exceptions. -
We call the
set_exceptionsfunction, which successfully sets all the flags defined in the function. -
To save this floating-point exception state, we call the
fegetexceptflagfunction. -
To test the
fesetexceptflagfunction, we raise two exceptions using theferaiseexceptfunction and set the state. -
The final step is calling the
fesetexceptflagfunction, which reinstates the previously saved state, as shown in the code below:
#include <stdio.h>#include <fenv.h>#pragma STDC FENV_ACCESS ON//Set the floating-point exception macrosvoid set_exceptions(){if(fetestexcept(FE_DIVBYZERO))printf(" FE_DIVBYZERO");if(fetestexcept(FE_INEXACT))printf(" FE_INEXACT");if(fetestexcept(FE_INVALID))printf(" FE_INVALID");if(fetestexcept(FE_OVERFLOW))printf(" FE_OVERFLOW");if(fetestexcept(FE_UNDERFLOW))printf(" FE_UNDERFLOW");if(fetestexcept(FE_ALL_EXCEPT)==0)printf(" none");printf("\n");}int main(){//Declare fexcept_t objectfexcept_t excepts;//Set the current execption flagsferaiseexcept(FE_UNDERFLOW);set_exceptions();//Save the flags by calling fegetexecptflagfegetexceptflag(&excepts,FE_ALL_EXCEPT);//Raise two exceptionsfeclearexcept(FE_ALL_EXCEPT);feraiseexcept(FE_OVERFLOW | (FE_DIVBYZERO));set_exceptions();// Restore the flags by calling fesetexecptflagfesetexceptflag(&excepts,FE_ALL_EXCEPT);set_exceptions();return 0;}
Free Resources