C Standard Library

C <fenv.h> - fesetenv() Function



The C <fenv.h> fesetenv() function attempts to establish the floating-point environment from the object pointed to by envp. Pointer to a fenv_t object that contains a floating-point environment must be previously obtained by a call to fegetenv() or feholdexcept() or equal to FE_DFL_ENV macro constant. If successful, the function changes the current state of the floating-point environment without actually raising the exceptions specified in such state.

Syntax

int fesetenv(const fenv_t* envp);

Parameters

envp Specify pointer to the object of type fenv_t which holds the status of the floating-point environment.

Return Value

Returns 0 on success. A non-zero value otherwise.

Exception

This function never throws exceptions.

Example:

The example below shows the usage of fesetenv() function.

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

#pragma STDC FENV_ACCESS ON

void FE_Exceptions_Message(void) {
  printf("Exceptions raised:");
  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");
}

void Rounding_Direction_Message(void) {
  printf("Current rounding method: ");
  switch(fegetround()) {
    case FE_DOWNWARD: 
      printf("DOWNWARD"); break;
    case FE_TONEAREST:   
      printf("TO-NEAREST"); break;
    case FE_TOWARDZERO:   
      printf("TOWARD-ZERO"); break;
    case FE_UPWARD:  
      printf("UPWARD"); break;
    default:
      printf("unknown");
  }
  printf("\n");
}

void FE_Environment_Message(void) {
  FE_Exceptions_Message();
  Rounding_Direction_Message();
  printf("\n");
}  

int main (){
  //creating fenv_t object
  fenv_t curr_env; 

  //displaying the current environment
  FE_Environment_Message();

  //storing the current environment
  fegetenv(&curr_env);

  //changing the current environment
  //and displaying it
  sqrt(-1);
  fesetround(FE_DOWNWARD);
  FE_Environment_Message();

  //restoring the previous environment
  //and displaying it
  fesetenv(&curr_env);
  FE_Environment_Message();

  return 0;
}

The output of the above code will be:

Exceptions raised: None
Current rounding method: TO-NEAREST

Exceptions raised: FE_INVALID
Current rounding method: DOWNWARD

Exceptions raised: None
Current rounding method: TO-NEAREST

❮ C <fenv.h> Library