4

Although Microsoft blogs claim otherwise using std::isnan in my code still does generate calls to c++ runtime instead of inlined ucomiss. Now I worked around that with x!=x check(since perf matters to me in this piece of code), but that made me wonder... If x!=x is a way to check for NaNess would that not be an easy way to implement std::isnan?

But from what I know gcc/clang use intrinsics (and msvc is trying). Why would they bother if it can be efficiently implemented as a normal function?

So I am a bit confused since one of the answers on SO claims that it is the only way selfcomparison can return false.

Evg
  • 25,259
  • 5
  • 41
  • 83
NoSenseEtAl
  • 28,205
  • 28
  • 128
  • 277

1 Answers1

5

The C++ standards committee (finally?) listened to the numericists on this one. Prior to C++11, the idiom

x != x

was indeed used to check for NaN-ness. There is no other class of values of a floating point number for which the idiom applies. But it never sat particularly well. For starters, some NaNs can raise exceptions. It's also vulnerable to errant refactoring. You could also be assuming some floating point standard, such as the commonplace IEEE754.

From C++11 onwards using std::isnan is much preferred.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • If I saw `x != x` in my codebase, I'd change it to false, just so it breaks and the author learns their lesson and uses clearer constructs like `isnan` – Jeffrey Jan 14 '21 at 17:55
  • @Jeffrey: In the old days I insisted it was written in a function. I never came across a compiler that optimised out the expression though - that would be a compiler bug. – Bathsheba Jan 14 '21 at 18:03