C library - fetestexcept() function



The C fenv library fetestexcept() function is used to check which of the specified floating-point exceptions are currently set through the 'excepts' parameter.

The excepts parameter is a bitwise OR combination of exception macros such as FE_DIVBYZERO, FE_INEXACT, FE_INVALID, FE_OVERFLOW, FE_UNDERFLOW, and FE_ALL_EXCEPT.

Syntax

Following is the C library syntax of fetestexcept() function −

int fetestexcept( int excepts );

Parameters

This function accepts a single parameter −

  • excepts − It represent a bitmask listing of the exception flags to test.

Return Value

This function returns an integer value that is a bitwise OR of the floating-point exception macros corresponding to the exception flags that are currently set among those specified by the excepts parameter.

Example 1

Following is the basic c program to demonstrate the use of fetestexcept() function.

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

int main() {
   // first clear all the exception
   feclearexcept(FE_ALL_EXCEPT);
   
   // divide by zero exception
   double result = 1.0 / 0.0;
   
   // Test which exception flags are set
   int flags = fetestexcept(FE_DIVBYZERO);
   
   if (flags & FE_DIVBYZERO) {
      printf("Divide by zero exception is set.\n");
   }
   else{
      printf("No exception is set. \n");
   }   
   return 0;
}

Output

Following is the output −

Divide by zero exception is set.

Example 2

The following program checks which types of floating-point exception we are getting using fetestexcept() function.

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

int main() {
   // first clear all the exception
   feclearexcept(FE_ALL_EXCEPT);

   double result = sqrt(-1.0);

   // Test which exception flags are set
   int flags = fetestexcept(FE_ALL_EXCEPT);

   if (flags & FE_DIVBYZERO) {
      printf("Divide by zero exception is set.\n");
   }
   if (flags & FE_INEXACT) {
      printf("Inexact result exception is set.\n");
   }
   if (flags & FE_INVALID) {
      printf("Invalid operation exception is set.\n");
   }
   if (flags & FE_OVERFLOW) {
      printf("Overflow exception is set.\n");
   }
   if (flags & FE_UNDERFLOW) {
      printf("Underflow exception is set.\n");
   }
   return 0;
}

Output

Following is the output −

Invalid operation exception is set.

Example 3

The example below checks for the overflow exception after multiplying large values.

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

int main() {
   // first Clear all exception flags
   feclearexcept(FE_ALL_EXCEPT);

   // overflow exception by multiplying large values
   double overflow_result = 1.0e300 * 1.0e300;

   // Test which exception flags
   int flags = fetestexcept(FE_OVERFLOW);
   if (flags & FE_OVERFLOW) {
      printf("Overflow exception is set.\n");
   }
   else {
      printf("No exception is set.\n");
   }
   return 0;
}

Output

Following is the output −

Overflow exception is set.
c_library_fenv_h.htm
Advertisements