Hasty Briefsbeta

Bilingual

Always use feenableexcept() when doing floating point math - Bert Hubert's writings

a day ago
  • Always use feenableexcept() in C/C++ floating point code to catch exceptions like division by zero, invalid operations, and overflow.
  • By default, ISO C silently allows infinities and NaNs, which can propagate and produce undetected bogus results in calculations.
  • Using feenableexcept(FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW) on Linux with -lm causes SIGFPE on dubious operations, crashing the program for safety.
  • Compiler optimization (e.g., SIMD) may be inhibited by exception trapping; enabling -fno-trapping-math allows optimization but prevents using feenableexcept().
  • Additional exceptions FE_UNDERFLOW and FE_INEXACT exist; FE_INEXACT is common and usually not useful for debugging.