C++ fesetenv()

The fesetenv() function in C++ attempts to set the floating-point environment from the given pointer object of type fenv_t.

The fesetenv() function is defined in <cfenv> header file.

fesetenv() prototype

int fesetenv( fenv_t* envp );

The fesetenv() function attempts to set the floating point environment from the object pointed to by envp. The value of envp must be previously obtained by a call to feholdexcept or fegetenv or be a floating-point macro constant.


fesetenv() Parameters

  • envp: Pointer to an object of type fenv_t that stores the status of the floating point environment.

fesetenv() Return value

  • On success, the fesetenv() function returns 0.
  • On failure, it returns nonzero.

Example: How fesetenv() function works?

#include <iostream>
#include <cmath>
#include <cfenv>
#pragma STDC FENV_ACCESS ON
using namespace std;

void print_exceptions()
{
	cout << "Raised exceptions: ";
	if(fetestexcept(FE_ALL_EXCEPT))
	{
		if(fetestexcept(FE_DIVBYZERO))
			cout << "FE_DIVBYZERO ";
		if(fetestexcept(FE_INEXACT))
			cout << "FE_INEXACT ";
		if(fetestexcept(FE_INVALID))
			cout << "FE_INVALID ";
		if(fetestexcept(FE_OVERFLOW))
			cout << "FE_OVERFLOW ";
		if(fetestexcept(FE_UNDERFLOW))
			cout << "FE_UNDERFLOW ";
	}
	else
		cout << "None";

	cout << endl;
}

void print_current_rounding_direction()
{
	cout << "Current rounding method: ";
	switch (fegetround()) {
		case FE_TONEAREST:
			cout << "FE_TONEAREST";
			break;
		case FE_DOWNWARD:
			cout << "FE_DOWNWARD";
			break;
		case FE_UPWARD:
			cout << "FE_UPWARD";
			break;
		case FE_TOWARDZERO:
			cout << "FE_TOWARDZERO";
			break;
		default:
			cout << "unknown";
	};
	cout << endl;
}

void print_environment()
{
	print_exceptions();
	print_current_rounding_direction();
}

int main(void)
{
	cout << "Initial environment " << endl;
	print_environment();
	fenv_t envp;

	/* Save current environment */
	fegetenv(&envp);
	feraiseexcept(FE_INVALID|FE_DIVBYZERO);
	fesetround(FE_DOWNWARD);
	cout << "After changing environment " << endl;
	print_environment();

	/* Restores previous environment */
	fesetenv(&envp);
	cout << "Restoring initial environment " << endl;
	print_environment();
	return 0;
}

When you run the program, the output will be:

Initial environment
Raised exceptions: None
Current rounding method: FE_TONEAREST
After changing environment
Raised exceptions: FE_DIVBYZERO FE_INVALID
Current rounding method: FE_DOWNWARD
Restoring initial environment
Raised exceptions: None
Current rounding method: FE_TONEAREST