What is fetestexcept in C?

fetestexcept() determines which of the floating-point exceptions are currently raised at any given moment during the program’s execution. It is defined in the fenv.h header. The full list of floating-point exception macros is available here.

The floating-point environment is a set of flags and modes that allow us to access and modify further information regarding any floating-point exceptions that have been raised.

We have to set #pragma STDC FENV_ACCESS to ON in order to use the floating-point environment in a meaningful way.

Prototype

int fetestexcept( int excepts );

Parameters

  • except: bitmask of all the exception flags to test.

Return Value

  • Bitwise OR of the floating-point exceptions included in the argument and the exceptions that are currently set.

Floating-point exceptions

Constant

Description

FE_DIVIDEBYZERO

Raised when the result of an earlier floating point operation is exactly infinity or negative infinity

FE_INEXACT

Raised when an the result of an earlier floating-point operation required rounding

FE_INVALID

Raised when domain error occurs

FE_OVERFLOW

Raised when the result of an earlier floating-point operation was too large to be contained

FE_UNDERFLOW

Raised when the magnitude of the result is too small to be contained

FE_ALLEXCEPT

Bitwise OR of all the above flags

#include<stdio.h>
#include<fenv.h>
#pragma STDC FENV_ACCESS ON
int main() {
// raise FE_DIVBYZERO exception
printf("2.0/0.0 = %f\n", 2.0/0.0);
if(fetestexcept(FE_DIVBYZERO)) printf("FE_DIVBYZERO exception raised!\n");
}

The above code shows how we can check for floating-point exceptions with fetestexcept(). Here, the code raises a FE_DIVIDEBYZERO exception because the result of the operation 2.0/0.0 is undefined.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved