function
<cfenv>

feholdexcept

int feholdexcept (fenv_t* envp);
Hold floating-point exceptions
Saves the current state of the floating-point environment in the object pointed by envp. It then resets the current state and -if supported- puts the environment in non-stop mode.

The non-stop mode prevents floating-point exceptions from stopping the normal flow of the program when raised (with traps or abortions).

Programs calling this function shall ensure that pragma FENV_ACCESS is enabled for the call.

Parameters

envp
Pointer to a fenv_t object where the state of the floating-point environment is stored.

Return Value

Zero, if the function completed successfully, including setting the floating point environment to non-stop mode.
A non-zero value otherwise.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/* feholdexcept/feupdateenv example */
#include <stdio.h>      /* printf, puts */
#include <fenv.h>       /* feholdexcept, feclearexcept, fetestexcept, feupdateenv, FE_* */
#include <math.h>       /* log */
#pragma STDC FENV_ACCESS on

double log_zerook (double x) {
  fenv_t fe;
  feholdexcept(&fe);
  x=log(x);
  feclearexcept (FE_OVERFLOW|FE_DIVBYZERO);
  feupdateenv(&fe);
  return x;
}

int main ()
{
  feclearexcept (FE_ALL_EXCEPT);
  printf ("log(0.0): %f\n", log_zerook(0.0));
  if (!fetestexcept(FE_ALL_EXCEPT))
    puts ("no exceptions raised");
  return 0;
}

Possible output:

log(0.0): -inf
no exceptions raised


Data races

Each thread maintains a separate floating-point environment with its own state. Spawning a new thread copies the current state. [This applies to C11 and C++11 implementations]

Exceptions

No-throw guarantee: this function never throws exceptions.
Note that C floating-point exceptions are not C++ exceptions, and thus are not caught by try/catch blocks.

See also