Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 451
Dave Avatar asked Dec 15 '10 20:12

Dave


People also ask

How do I know if my float is NaN?

To check whether a floating point or double number is NaN (Not a Number) in C++, we can use the isnan() function. The isnan() function is present into the cmath library. This function is introduced in C++ version 11.

What makes a float NaN?

NaN stands for Not A Number and is one of the common ways to represent the missing value in the data. It is a special floating-point value and cannot be converted to any other type than float. NaN value is one of the major problems in Data Analysis.

What is the value of NaN in C?

An expression representing positive infinity. It is equal to the value produced by mathematical operations like 1.0 / 0.0 .

How do I get NaN in C++?

CPP. Another way to check for NaN is by using “isnan()” function, this function returns true if a number is complex else it returns false. This C library function is present in <cmath> header file.


2 Answers

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; } 
like image 165
watson1180 Avatar answered Sep 20 '22 03:09

watson1180


Try enabling fp exceptions

like image 41
Gene Bushuyev Avatar answered Sep 21 '22 03:09

Gene Bushuyev