Visual Studio C++ 2008 / 2010 - break on float NaN

Dave picture Dave · Dec 15, 2010 · Viewed 10.4k times · Source

Is there any way to set up Visual Studio (just upgraded from 2008 to 2010) to break, as if an assertion failed, whenever any floating point number becomes NaN, QNAN, INF, etc?

Up until now I have just been using the assert(x == x) trick, but I would rather something implicit, so that I dont have to add assertions everywhere.

Quite surprised I can't find an answer to this via google. Some stuff about 'floating point exceptions', but I'm not sure if they are the same thing, and I've tried enabling them in Visual Studio, but the program doesn't break until something catastrophic happens because of the NaN later on in execution.

Answer

watson1180 picture watson1180 · Dec 15, 2010

1) Go to project option and enable /fp:strict (C/C++ -> Code Generation -> Floating Pint Model).

2) Use _controlfp to set the floating-point control word (see code below).

#include <float.h>
unsigned int fp_control_state = _controlfp(_EM_INEXACT, _MCW_EM);

#include <math.h>

int main () {

    sqrtf(-1.0);    // floating point exception

    double x = 0.0;
    double y = 1.0/x;   // floating point exception

    return 0;
}