0

I'm trying to understand the strange behavior of the following program. Obviously, an overflow occurs during the definition of the global variable "bug", but the program throws a floating point exception during the innocent calculation 1.0+2.0.

#include <iostream>
#include <cmath>
#include <fenv.h>

using namespace std;

const double bug = pow(10.0,pow(10.0,10.0));

int main(void)
{
  feenableexcept(-1);

  cout << "before" << endl;
  cout << 1.0 + 2.0 << endl;
  cout << "after" << endl;

  return 0;
}

I tried compiling it with both g++ and clang++, but got the same output in both

before
Floating point exception
user2535797
  • 529
  • 3
  • 10
  • I'm not sure, but possibly because the exception flag is set when you enable them, but it isn't tested until you perform the addition. – molbdnilo Feb 04 '14 at 09:05

2 Answers2

1

const double bug = pow(10.0,pow(10.0,10.0)); should be used. Because pow need (double,double) argument and you are passing (int,int)

Pranit Kothari
  • 9,721
  • 10
  • 61
  • 137
0

Once I encountered similar case when floating point error manifested itself at strange places. As I understood this happened because FPU status register is syncronized not during every floating point instruction so error may appear to be random. By the way, I've just compiled and started your program and it finished without any issues. My solution was to clear FPU status register after faulty calculation (of course this is hack but at that time I couldn't analize that math library).

AlexT
  • 1,413
  • 11
  • 11