Related Tags

c++

# How to use fetestexcept() in C++

fetestexcept() tests for the floating-point exceptions that have been raised at any given moment in a program’s execution. It is defined in the cfenv header along with the floating-point exception macros.

To use fetestexcept(), the program must enable the pragma FENV_ACCESS as shown below:

#pragma STDC FENV_ACCESS on


## Prototype

int fetestexcept (int excepts);


## Parameters

except: a bitmask of type int which specifies the floating-point exceptions to test for.

## Return value

fetestexcept() returns bitwise OR of the floating point exceptions that are currently set and the bitmask provided as the argument.

Floating point exception macros
 Macro Description FE_DIVBYZERO the result of a computation with finite arguments is infinite (division by zero occurs) FE_INEXACT the result of a computation can not be represented with exact accuracy FE_INVALLID the function is undefined for at least one of the given arguments FE_OVERFLOW the resulting value is too large to be represented by a floating point value FE_UNDERFLOW the resulting value is too small to be represented by a floating point value FE_ALL_EXCEPT at least one of the above exceptions are raised

## Example

#include <iostream>
#include <cmath>
#include <cfenv>

#pragma STDC FENV_ACCESS on

int main(){

float x = 1.0 / 0.0;
float y = std::sqrt(-1);

std::cout << "The floating point exceptions currently raised are: " << std::endl;

if (std::fetestexcept(FE_DIVBYZERO)) std::cout << "FE_DIVBYZERO raised" << std::endl;
if (std::fetestexcept(FE_INEXACT)) std::cout << "FE_INEXACT raised" << std::endl;
if (std::fetestexcept(FE_INVALID)) std::cout << "FE_INVALID raised" << std::endl;
if (std::fetestexcept(FE_OVERFLOW)) std::cout << "FE_OVERFLOW raised" << std::endl;
if (std::fetestexcept(FE_UNDERFLOW)) std::cout << "FE_UNDERFLOW raised" << std::endl;
if (std::fetestexcept(FE_ALL_EXCEPT)) std::cout << "FE_ALL_EXCEPT raised" << std::endl;
else
std::cout << "**No exceptions raised**" << std::endl;

return 0;
}

In the code above, we trigger the FE_DIVBYZERO and the FE_INVALID exceptions to be set.

FE_DIVBYZERO is raised when we try to compute the result of $1.0/0.0$, which is undefined. As a result, it raises the FE_DIVBYZERO exception.

FE_INVALID is raised when we try to compute the square root of $-1$. Since the square root is only defined for positive values, it raises the FE_INVALID exception.

RELATED TAGS

c++

CONTRIBUTOR