C Standard Library

C <fenv.h> - fetestexcept() Function



The C <fenv.h> fetestexcept() function returns the floating point exceptions currently set, among those specified by excepts. The argument excepts is a bitwise OR of the floating point exception macros and the value returned by the function is the bitwise OR representation of the subset of excepts that are currently set in the floating point environment.

Syntax

int fetestexcept (int excepts);

Parameters

excepts

Specify bitmask listing the floating-point exception flags to test.

MacrosDescription
FE_DIVBYZERO Pole error exception occurred in an earlier floating-point operation.
FE_INEXACT Inexact result exception occurred in an earlier floating-point operation (rounding was necessary to store the result).
FE_INVALID Invalid argument exception occurred (domain error occurred) in an earlier floating-point operation.
FE_OVERFLOW Overflow range error exception occurred in an earlier floating-point operation (result was too large to be representable).
FE_UNDERFLOW Underflow range error exception occurred in an earlier floating-point operation (result was subnormal with a loss of precision).
FE_ALL_EXCEPT Bitwise OR of all supported floating-point exceptions.

Certain library implementations may define additional macro constants in <fenv.h> to identify additional floating-point exceptions (with their corresponding macros also beginning with FE_).

Return Value

Returns 0 if none of the exceptions in excepts are set. Otherwise returns the exceptions (among those of excepts) currently set.

Exception

This function never throws exceptions.

Example:

In the example below, the fetestexcept() function is used to clear floating-point exceptions.

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

#pragma STDC FENV_ACCESS ON

void Show_Exceptions() {
  if(fetestexcept(FE_DIVBYZERO)) 
    printf("Exceptions raised: FE_DIVBYZERO \n");
  if(fetestexcept(FE_INEXACT))   
    printf("Exceptions raised: FE_INEXACT \n");
  if(fetestexcept(FE_INVALID))   
    printf("Exceptions raised: FE_INVALID \n");
  if(fetestexcept(FE_OVERFLOW))  
    printf("Exceptions raised: FE_OVERFLOW \n");
  if(fetestexcept(FE_UNDERFLOW)) 
    printf("Exceptions raised: FE_UNDERFLOW \n");
  if(fetestexcept(FE_ALL_EXCEPT) == 0) 
    printf("Exceptions raised: None \n");
}

int main (){
  printf("On startup: \n");
  Show_Exceptions();

  //raising FE_INVALID and FE_INEXACT exceptions
  feraiseexcept(FE_INVALID | FE_INEXACT);

  printf("\nBefore restoration:\n");
  Show_Exceptions();

  //resetting to default environment
  fesetenv(FE_DFL_ENV);

  printf("\nAfter reset to default:\n");
  Show_Exceptions();

  return 0;
}

The output of the above code will be:

On startup: 
Exceptions raised: None 

Before restoration:
Exceptions raised: FE_INEXACT 
Exceptions raised: FE_INVALID 

After reset to default:
Exceptions raised: None 

❮ C <fenv.h> Library