C++ Standard Library C++ STL Library

C++ <cfenv> - FENV_ACCESS



The floating-point environment is the set of floating-point status flags and control modes supported by the implementation. It is thread-local, each thread inherits the initial state of its floating-point environment from the parent thread. Floating-point operations modify the floating-point status flags to indicate abnormal results or auxiliary information. The state of floating-point control modes affects the outcomes of some floating-point operations.

By default, FENV_ACCESS (floating-point environment access) is off. The compiler assumes that the code doesn't access or manipulate the floating-point environment. Hence, the compiler may perform certain optimizations that can subvert these tests and mode changes, and thus accessing the floating-point environment in the cases described above, causes undefined behavior.

If FENV_ACCESS is set to on, the program informs the compiler that it might access the floating-point environment to test its status flags (exceptions) or run under control modes other than the one by default.

When the state is changed by this pragma directive, the floating-point control modes (such as rounding direction) have their default settings, but the state of the floating point status flags is unspecified.

Syntax

//floating-point environment on
#pragma STDC FENV_ACCESS on

//floating-point environment off  
#pragma STDC FENV_ACCESS off 

Example:

The example below shows the usage of FENV_ACCESS pragma.

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

//setting the FENV_ACCESS on
#pragma STDC FENV_ACCESS ON

using namespace std;
 
int main (){
  cout<<"sqrt(-1.0) = "<<sqrt(-1)<<"\n";
  if(fetestexcept(FE_INVALID))
    cout<<"Domain error is reported.\n";
  else
    cout<<"Domain error is not reported.\n";

  return 0;
}

The output of the above code will be:

sqrt(-1.0) = -nan
Domain error is reported.

❮ C++ <cfenv> Library