Feclearexcept In C++ - C++ Programming Tutorial
C++ Course / Miscellaneous / Feclearexcept In C++

Feclearexcept In C++

BLUF: Mastering Feclearexcept In C++ is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Feclearexcept In C++

C++ is renowned for its efficiency. Learn how Feclearexcept In C++ enables low-level control and high-performance computing in the tutorial below.

In this guide, you will explore the feclearexcept function in C++ along with its syntax, parameters, and sample illustrations.

What is the feclearexcept method?

You have the option to utilize the C++ function feclearexcept to reset the floating-point exception flag triggered during a floating-point condition evaluation. These flags indicate different anomalies that may arise during floating-point arithmetic computations, including zero division, overflow, underflow, invalid operation, and inaccurate outcomes.

The match flag is activated within the floating-point condition specification upon the triggering of a floating-point exception. This enables the program to identify and react to these atypical scenarios. Managing the exception and resetting the flag is frequently essential to prevent interference with subsequent floating-point operations. The feclearexcept function proves to be valuable in addressing this particular scenario.

Syntax:

It has the following syntax:

Example

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

If there are no exceptions or if all exceptions have been cleared, the feclearexcept function will return a value of zero. In case of an error, a non-zero value will be returned.

The floating-point environment control function of the C standard library is described in the <cfenv> header and includes the feclearexcept function. It can be used to set one or more floating-point exception flags. The only input required for the function is a bitwise OR of one or more of the following constants:

  • (FE_DIVBYZERO): Division by zero exception flag.
  • (FE_INEXACT): Flag for incorrect result exclusion.
  • (FE_INVALID): Invalid operation exception flag.
  • (FE_OVERFLOW): Exceptional overflow.
  • (FE_UNDERFLOW): Additional for underflow.
  • Program 1:

Let's consider a scenario to demonstrate the usage of the feclearexcept function in C++.

Example

#include <cfenv>
#include <iostream>
int main() {
    // Clear the division by zero and overflow exception flags
    feclearexcept(FE_DIVBYZERO | FE_OVERFLOW);
    // Check if the flags are cleared
    if (!fetestexcept(FE_DIVBYZERO) && !fetestexcept(FE_OVERFLOW)) {
        std::cout << "Division by zero and overflow exception flags cleared\n";
    } else {
        std::cout << "Failed to clear division by zero and overflow exception flags\n";
    }
    return 0;
}

Output:

Program 2:

Let's consider another example to demonstrate the feclearexcept function in the C++ programming language.

Example

#include <fenv.h> 
#include <iostream> 
#include <math.h> 
#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:

Program 3:

Let's consider another example to demonstrate the feclearexcept function in C++.

Example

#include <iostream>
#include <cmath>
#include <limits>
#include <cfenv>
int main() {
    // Perform a floating-point operation that sets the overflow flag
    double result = std::numeric_limits<double>::max() * 2.0;
    // Check if the overflow flag is set
    if (std::fetestexcept(FE_OVERFLOW)) {
        std::cout << "Overflow detected\n";
    }
    // Clear all floating-point exception flags
    std::fexcept_t flag;
    std::feclearexcept(FE_ALL_EXCEPT);
    // Check if all flags are cleared
    if (!std::fetestexcept(FE_ALL_EXCEPT)) {
        std::cout << "All floating-point exception flags cleared\n";
    } else {
        std::cout << "Failed to clear all floating-point exception flags\n";
    }
    return 0;
}

Output:

Program 4:

Let's consider a scenario to demonstrate the feclearexcept function within C++.

Example

#include <fenv.h>
#include <stdio.h>
#include <math.h>
#include <float.h>
double hypot_demo(double a, double b) {
  const int range_problem = FE_OVERFLOW | FE_UNDERFLOW;
  feclearexcept(range_problem);
  double result = sqrt(a * a + b * b);
  if (!fetestexcept(range_problem))  // no overflow or underflow
    return result
  //Do a more complicated calculation to avoid overflow or underflow
  int a_exponent,b_exponent;
  frexp(a, &a_exponent);
  frexp(b, &b_exponent);
  if (a_exponent - b_exponent > DBL_MAX_EXP)
    return fabs(a) + fabs(b);        
  double a_scaled = scalbn(a, -a_exponent);
  double b_scaled = scalbn(b, -a_exponent);
  //Overflow and underflow 
  result = sqrt(a_scaled * a_scaled + b_scaled * b_scaled);
  // undo scaling
  return scalbn(result, a_exponent);
}
int main(void)
{
  printf("hypot(%f, %f) = %f\n", 1.0, 2.0, hypot_demo(1.0, 2.0));
  printf("hypot(%e, %e) = %e\n", DBL_MAX / 2.0, 
                                DBL_MAX / 2.0, 
                                hypot_demo(DBL_MAX / 2.0, DBL_MAX / 2.0))
  return 0;
}

Output:

Advantages of the Feclearexcept Method:

There are several advantages of the Feclearexcept Method in C++. Some main advantages of the Feclearexcept Method are as follows:

  • Specificity in exception handling: By clearing special flags when necessary, feclearexcept enables floating-point exceptions to be handled more precisely, which can help preserve statistical accuracy and integrity
  • Control Flow: Developers can improve program robustness by selecting flags to control the execution flow of a program in response to the presence or absence of specific exceptions
  • Debugging: By providing a tool to reset exception flags and isolate complex calculations, feclearexcept can help troubleshoot floating point issues.
  • Limitations of the Feclearexcept Method:

There are several limitations of the Feclearexcept Method in C++. Some main limitation of the Feclearexcept Method are as follows:

  • Limited scope: feclearexcept only handles floating-point exception flags; It cannot handle other exceptions or system errors.
  • Manual handling: Developers should use feclearexcept to clear exception flags manually, which can be labor-intensive and error-prone if not handled properly.
  • Environment dependency: Feclearexcept assumes that its behavior is dependent on the underlying floating-point environment, which may vary between platforms and compilers.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience