C library - feupdateenv() function



The C fenv library feupdateenv() function is used to restore the floating-point environment. It also handle the exceptions during the occurance of environment saved with feholdexcept. The feholdexcept can restore the original environment to restore the exception.

Syntax

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

feupdateenv(const fenv_t *envp);

Parameters

This function accepts only a single parameter −

  • It takes a pointer to an fenv_t object that raise the exception handler.

Return Value

  • On success of program compilation, it returns the value in integer form which is zero. Also, it returns non-zero value when exception cannot be raised.

Example 1

Following is the C library program to shows the usage of feupdateenv() function.

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

int main() {
   fenv_t env;
   
   // Save and clear exceptions
   feholdexcept(&env); 

   // Restore the environment and raise exceptions
   feupdateenv(&env); 
   printf("Environment restored, exceptions handled.\n");
   return 0;
}

Output

The above code produces the following result −

Environment restored, exceptions handled.

Example 2

To save and clear the exception, we can perform the task of division by zero which restore the environment and check whether the exception has occured or not.

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

int main() {
   fenv_t env;
   
   // Save and clear exceptions
   feholdexcept(&env); 

   // Division by zero
   double result = 1.0 / 0.0; 

   // Restore the environment and handle exceptions
   feupdateenv(&env); 
   if (fetestexcept(FE_DIVBYZERO)) {
       printf("Division by zero occurred and handled.\n");
   }
   return 0;
}

Output

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

Division by zero occurred and handled.

Example 3

To restore the original environment, it performs the task of raise and overflow exceptions along with that it also executes the same program that we did in example 2(saves and clear exception).

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

int main() {
   fenv_t env1, env2;
   // Save and clear exceptions
   feholdexcept(&env1);    
   
   // Raise an overflow exception
   feraiseexcept(FE_OVERFLOW); 
   
   // Save and clear exceptions again
   feholdexcept(&env2); 

   // Restore the original environment
   feupdateenv(&env1); 
   printf("Original environment restored.\n");
   return 0;
}

Output

After executing the above code, we get the following result −

Original environment restored.
c_library_fenv_h.htm
Advertisements