C Standard Library

C <math.h> - math_errhandling, MATH_ERRNO, MATH_ERREXCEPT



The C <math.h> 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 <math.h> 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 <stdio.h>
#include <fenv.h>
#include <math.h>
#include <errno.h>
#include <string.h>
#include <float.h>

#pragma STDC FENV_ACCESS ON

int main (){

  printf("MATH_ERRNO is %s\n",
      (math_errhandling & MATH_ERRNO ? "set" : "not set"));
  printf("MATH_ERREXCEPT is %s\n",
      (math_errhandling & MATH_ERREXCEPT ? "set" : "not set"));
  
  errno = 0;
  printf("\nlog(0) = %f\n", log(0));
  if(errno == ERANGE)
    printf("errno = ERANGE ( %s )\n", strerror(errno));
  if(fetestexcept(FE_DIVBYZERO))
    printf("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 <math.h> Library

5