C++ Standard Library C++ STL Library

C++ <cmath> - math_errhandling, MATH_ERRNO, MATH_ERREXCEPT



The C++ <cmath> math_errhandling macro constant expands to an expression of type int that is either equal to MATH_ERRNO, or equal to MATH_ERREXCEPT, or equal to their bitwise OR (MATH_ERRNO | MATH_ERREXCEPT). The value of math_errhandling indicates the type of error handling that is performed by the floating-point operators and functions.

ConstantValueDescription
MATH_ERRNO1 errno is used to signal errors:
  • On domain error: errno is set to EDOM.
  • On pole error and Range error due to overflow: errno is set to ERANGE.
  • On Range error due to underflow: errno is set to ERANGE or unchanged (implementation-defined).
  • On Inexact result: errno remains unchanged.
MATH_ERREXCEPT2 The C exception is raised:
  • On domain error: FE_INVALID is raised.
  • On pole error: FE_DIVBYZERO is raised.
  • On Range error due to overflow: FE_OVERFLOW is raised.
  • On Range error due to underflow: FE_UNDERFLOW is raised or nothing (implementation-defined).
  • On Inexact result: FE_INEXACT is raised or nothing (implementation-defined).
MATH_ERRNO | MATH_ERREXCEPT3 Both of the above

Definition in the <cmath> header file is:

#define MATH_ERRNO        1
#define MATH_ERREXCEPT    2
#define math_errhandling  /* implementation defined */                        

Example:

The example below shows the usage of following macros.

#include <iostream>
#include <cfenv>
#include <cmath>
#include <cerrno>
#include <cstring>
#include <cfloat>

#pragma STDC FENV_ACCESS ON

using namespace std;

int main (){

  cout<<"MATH_ERRNO is "
      <<(math_errhandling & MATH_ERRNO ? "set" : "not set")<<endl;
  cout<<"MATH_ERREXCEPT is "
      <<(math_errhandling & MATH_ERREXCEPT ? "set" : "not set")<<endl;
  
  errno = 0;
  cout<<"\nlog(0) = "<<log(0)<<endl;
  if(errno == ERANGE)
    cout<<"errno = ERANGE ("<<strerror(errno)<<")\n";
  if(fetestexcept(FE_DIVBYZERO))
    cout<<"FE_DIVBYZERO (pole error) reported\n";

  return 0;
}

The output of the above code will be:

MATH_ERRNO is set
MATH_ERREXCEPT is set

log(0) = -inf
errno = ERANGE (Numerical result out of range)
FE_DIVBYZERO (pole error) reported

❮ C++ <cmath> Library