feholdexcept() in C/C++
Last Updated :
28 Apr, 2022
The feholdexcept() function in C/C++ first saves the current floating-point environment in the object of fenv_t and it then resets the current values of all the floating point status flags. The feholdexcept() function is defined in cfenv header file in C++ and in fenv.h header file in C.
Syntax:
int feholdexcept( fenv_t* envp )
Parameters: The function accepts a single mandatory parameter envp which is a pointer to an object
of type fenv_t that stores the current status of the floating point environment.
Return Value: The function returns a int value on two conditions:
- If function completed successfully it returns 0.
- On failure, it returns a nonzero integer.
Below programs illustrate the above function.
Program 1:
CPP
#include <bits/stdc++.h>
#pragma STDC FENV_ACCESS on
double divide( double x, double y)
{
fenv_t envp;
double ans = x / y;
feholdexcept(&envp);
feclearexcept(FE_OVERFLOW | FE_DIVBYZERO);
return ans;
}
int main()
{
feclearexcept(FE_ALL_EXCEPT);
double x = 10;
double y = 0;
printf ( "x/y = %f\n" , divide(x, y));
if (!fetestexcept(FE_ALL_EXCEPT)) {
printf ( "No exceptions raised" );
}
return 0;
}
|
Output:
x/y = inf
No exceptions raised
Program 2:
CPP
#include <bits/stdc++.h>
#pragma STDC FENV_ACCESS on
using namespace std;
void raised_exceptions()
{
cout << "Exceptions raised are : " ;
if (fetestexcept(FE_DIVBYZERO))
cout << " FE_DIVBYZERO\n" ;
else if (fetestexcept(FE_INVALID))
cout << " FE_INVALID\n" ;
else if (fetestexcept(FE_OVERFLOW))
cout << " FE_OVERFLOW\n" ;
else if (fetestexcept(FE_UNDERFLOW))
cout << " FE_UNDERFLOW\n" ;
else
cout << " No exception found\n" ;
return ;
}
int main()
{
fenv_t envp;
feraiseexcept(FE_DIVBYZERO);
raised_exceptions();
feholdexcept(&envp);
raised_exceptions();
feupdateenv(&envp);
raised_exceptions();
return 0;
}
|
Output:
Exceptions raised are : FE_DIVBYZERO
Exceptions raised are : No exception found
Exceptions raised are : FE_DIVBYZERO
Share your thoughts in the comments
Please Login to comment...