feclearexcept in C++ with Examples

feclearexcept() clears the supported floating-point exceptions represented by excepts.
Syntax:

int feclearexcept(int excepts);
excepts : Bitmask listing of exception flags to clear

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.

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.

// Cpp program to demonstrate
// feclearexcept()
#include <fenv.h> /* feclearexcept FE_ALL_EXCEPT, FE_INVALID */
#include <iostream> /* cout */
#include <math.h> /* sqrt */
#pragma STDC FENV_ACCESS on
using namespace std;

int main()
{
    feclearexcept(FE_ALL_EXCEPT);
    sqrt(-1);
    if (fetestexcept(FE_INVALID))
        cout << "sqrt(-1) raises FE_INVALID" << endl;
    return 0;
}
Output:

sqrt(-1) raises FE_INVALID

How feclearexcept() works?

// Cpp program to demonstrate
// feclearexcept()
#include <cfenv>
#include <cmath>
#include <iostream>
#pragma STDC FENV_ACCESS ON
using namespace std;

int main()
{
    // clears all exceptions
    feclearexcept(FE_ALL_EXCEPT);
    cout << "7/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(-5) = " << sqrt(-5) << endl;

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

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


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.




Practice Tags :
Article Tags :
Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.

Recommended Posts:



0 Average Difficulty : 0/5.0
No votes yet.






User Actions