C library - feholdexcept() function



The C fenv library feholdexcept() function is used to perform the task of floating-point operations that may raise exceptions without interrupting the flow of the program.

On succession of program compilation, we can restore the original environment to restore the exception.

Syntax

Following is the C library syntax of the feholdexcept() function.

feholdexcept(fenv_t *envp);

Parameters

  • The function takes a pointer to an fenv_t object where the current environment will be stored before clearing the flags(floating-point operation).

Return Value

This function returns an integer value, which is −

  • zero, if the program works.

  • non-zero, if environment cannot be set.

Example 1

feholdexcept()

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

int main() {
   fenv_t env;
   
   // Save and clear all exceptions
   feholdexcept(&env); 
   
   // Restore the saved exceptions
   fesetenv(&env); 
   printf("Exceptions restored.\n");
   return 0;
}

Output

The above code produces the following result −

Exceptions restored.

Example 2

Below the program saves and clears exceptions to perform operations without stopping for division by zero, then checks if such an exception occurred.

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

int main() {
   fenv_t env;
   
   // Save and clear exceptions
   feholdexcept(&env); 
   
   // Perform operations that may raise exception
   if (fetestexcept(FE_DIVBYZERO)) {
       printf("Division by zero occurred, but calculations continued.\n");
   }
   // Restore the environment to handle exceptions properly
   fesetenv(&env);
   return 0;
}

Output

On execution of above code, we get the following result −

=== Code Execution Successful ===
c_library_fenv_h.htm
Advertisements