3

of course I know I should write better code which just not create NaN values. But is there any casual method to avoid it. I mean something like:

if (!(floatNumber == NaN))
   // do some stupid function
else
return;

But it doesn't work for me. I also tried floatNumber==null, but also no result. Could you please help me?

pajczur
  • 235
  • 3
  • 10
  • OK, Thanks for info, but could you provide any link to that duplicated thread, that I could read it and find the answer? – pajczur Apr 20 '18 at 07:47

1 Answers1

6

To test whether a number is NaN, you can use the standard library function std::isnan.

user4815162342
  • 141,790
  • 18
  • 296
  • 355
  • Thanks, but how to use it? Something like that? `if(floatNumber == std::isnan)` or some other way? – pajczur Apr 20 '18 at 07:47
  • @pajczur You call it with a floating-point number to check if it's NaN. In other words, instead of `if (!(floatNumber == NaN))`, you'd write `if (!std::isnan(floatNumber))` – user4815162342 Apr 20 '18 at 07:49
  • Then let those who come after apply floating point optimization option, and u have a bug. That is, this answer is advice to write brittle code. – Cheers and hth. - Alf Apr 20 '18 at 09:53
  • @Cheersandhth.-Alf Since when is a documented standard library function "brittle code"? – user4815162342 Apr 20 '18 at 11:52
  • @user4815162342: If you're referring to `std::isnan`, that's since C++11. It's not the standard's fault though. It's the implementations that fail to do this properly, and that's the reality that you need to relate to. – Cheers and hth. - Alf Apr 20 '18 at 12:34
  • @Cheersandhth.-Alf That sounds like an issue that should be reported to the compiler vendor. If my understanding is correct, it doesn't even happen with the default flags? – user4815162342 Apr 20 '18 at 12:51
  • @user4815162342: Vendors plural. And you're right, the default behavior is that it works. That's why the code is *brittle*, not straight incorrect. – Cheers and hth. - Alf Apr 20 '18 at 13:13
  • @Cheersandhth.-Alf The code - or rather, the recommendation to use the standard library - is fine, it's the combination of buggy compiler and its non-standard switch that is _brittle_. – user4815162342 Apr 20 '18 at 13:32