4

I have a complex model written in C++ where denominators sometimes happens to be zeros. I normally check for them, but when I forgot, it's a pain to debug them as the model continues without warnings.

Is there a compiler flag, working in both recent versions of gcc in linux and MinGW on windows, that I can use to tell gcc to compile as to raise a runtime error when (between doubles) division by zero happens ? Is this computationally expensive (so to enable it only in debug builds) ?

I am aware of a similar question that has been posted here, but the answers are more a mix of technical and theoretical quick comments rather than a developed answer.

Community
  • 1
  • 1
Antonello
  • 6,092
  • 3
  • 31
  • 56

2 Answers2

1

For gcc in linux you can use fenv.h or since c++11 cfenf and on windows there is _controlfp

Ari Hietanen
  • 1,749
  • 13
  • 15
0

The best I could find for now is to do the check in Linux and ignore it in MinGW (_controlfp seems not to work on my installation). This is not a problem in my user-case, as the development happens anyhow in Linux:

#include <iostream>

#ifdef  __GNUC__
#ifndef __MINGW32__
//#define _GNU_SOURCE // contrary to other answers, this seems no longer  needed as defined by default
#include <fenv.h>
#endif
#endif

int main(int argc, char* argv[]){
#ifdef  __GNUC__
#ifndef __MINGW32__
  feenableexcept(FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW);
#endif
#endif
  double num = 4.0;
  double den = 0.0;
  double ratio = num/den;
  std::cout << "ratio: " << ratio << std::endl;
}
Antonello
  • 6,092
  • 3
  • 31
  • 56