Search code examples
c++gccfloating-pointsigfpe

Division by zero does not throw SIGFPE


I have a small program performing floating-point division by zero, so I expect SIGFPE.

#include <sys/types.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>

void signal_handler (int signo) {
    if(signo == SIGFPE) {
      std::cout << "Caught FPE\n";
    }
}

int main (void) {
  signal(SIGFPE,(*signal_handler));

  double b = 1.0;
  double c = 0.0;
  double d = b/c;
  std::cout << "d = "<< d << std::endl;
  return 0;
}

Actually, I got the following output:

d = inf

gcc version 4.5.2 (Ubuntu/Linaro 4.5.2-8ubuntu4)

What should I do to throw SIGFPE in this case? Which factors FP operation behaviour depend on (compiler flags/CPU type and so on)?

Thanks


Solution

  • For floating point numbers you can change this behavior by setting up FPU control word. Take a look here