Is there a compiler flag for gcc (Linux / MinGW) to increase the division by zero error at runtime?

I have a complex model written in C ++ where denominators sometimes turn out to be zeros. I usually test them, but when I forget, it's a pain to debug them, as the model continues without warning.

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

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

+4
source share
2 answers

For gcc on linux you can use fenv.h or with c ++ 11 cfenf , and there is _ controlfp in windows

+1
source

The best I can find now is to do a check in Linux and ignore it in MinGW (_controlfp doesn't seem to work on my installation). This is not a problem in my user case, since development still happens on 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;
}
0
source

Source: https://habr.com/ru/post/1614288/


All Articles