C++ fesetexceptflag()

The fesetexceptflag() function in C++ sets specified floating point exception flags from a pointer object into the floating point environment.

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

fesetexceptflag() prototype

int fesetexceptflag( const fexcept_t* flagp, int excepts );

The fesetexceptflag() function attempts to copy all the contents of the floating-point exception flags specified by excepts from flagp into the floating point environment.

This function only modifies the flags and does not raise any exceptions.


fesetexceptflag() Parameters

  • flagp: A pointer to an fexcept_t object where the flags will be read from.
  • excepts: Bitmask listing of exception flags to set.
Bitmask accepted macros
Macro Type Description
FE_DIVBYZERO Pole error Division by zero
FE_INEXACT Inexact Not exact results such as (1.0/3.0)
FE_INVALID Domain error At least one arguments used is a value for which the function is not defined
FE_OVERFLOW Overflow range error Result is too large in magnitude to be represented by the return type
FE_UNDERFLOW Underflow range error Result is too small in magnitude to be represented by the return type
FE_ALL_EXCEPT All exceptions All exceptions supported by the implementation

fesetexceptflag() Return value

  • The fesetexceptflag() function returns zero on success, nonzero otherwise.

Example: How fesetexceptflag() function works?

#include <iostream>
#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;
}

int main()
{
	fexcept_t excepts;
	feraiseexcept(FE_DIVBYZERO);
	
	/* save current state*/
	fegetexceptflag(&excepts,FE_ALL_EXCEPT);
	print_exceptions();
	feraiseexcept(FE_INVALID|FE_OVERFLOW);
	print_exceptions();
	
	/* restoring previous exceptions */
	fesetexceptflag(&excepts,FE_ALL_EXCEPT);
	print_exceptions();
	
	return 0;
}

When you run the program, the output will be:

Raised exceptions: FE_DIVBYZERO
Raised exceptions: FE_DIVBYZERO FE_INVALID FE_OVERFLOW
Raised exceptions: FE_DIVBYZERO