Turning off floating point exceptions against crashes

It sounds quite mad, but either of these lines can crash a program: (C++, Visual Studio 2005)

long x = long(my_float_var);
float f = exp(my_float_var);

If the number is too large/small, the program is terminated. (No, try/catch doesn’t help.) And to make it even stranger, this happens only on some computers. And of course it happened on the customer’s computer and not on mine…

To fix this, it helps to turn off the floating point exceptions:
control87(_EM_INVALID|_EM_DENORMAL|_EM_ZERODIVIDE|_EM_OVERFLOW|_EM_UNDERFLOW|_EM_INEXACT, _MCW_EM);

Of course the problem of the large number still exists, but now the program at least continues to run, and I have a chance to handle it.

Leave a Reply

You must be logged in to post a comment.