C++ feclearexcept()

The feclearexcept() function in C++ attempts to clear the floating point exception flags specified by the argument excepts.

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

feclearexcept() Prototype

int feclearexcept(int excepts);

For the function to work, you should enable FENV_ACCESS, which will give your program to access the Floating point environment to test the exceptions raised.


feclearexcept() Parameters

  • excepts: Bitmask listing of exception flags to clear
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

feclearexcept() Return value

  • The feclearexcept() function returns zero value if all the exceptions were cleared or if excepts is equal to zero.
  • It returns nonzero if any error occurs.

Example: How feclearexcept() function works?

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

int main()
{
	// clears all exceptions
	feclearexcept(FE_ALL_EXCEPT);
	cout << "1/0 = " << 1.0/0.0 << endl;
	
	// tests if above statement raised the FE_DIVBYZERO exception
	if(fetestexcept(FE_DIVBYZERO))
	{
		cout << "FE_DIVBYZERO is set" << endl;
	}
	else
	{
		cout << "FE_DIVBYZERO is not set" << endl;
	}

	feclearexcept(FE_ALL_EXCEPT);
	cout << "sqrt(-1) = " << sqrt(-1) << endl;

	if(fetestexcept(FE_INVALID))
	{
		cout << "FE_INVALID is set" << endl;
	}
	else
	{
		cout << "FE_INVALID is not set" << endl;
	}
}

When you run the program, the output will be:

1/0 = inf
FE_DIVBYZERO is set
sqrt(-1) = -nan
FE_INVALID is set