Optimal code generation for std::isnan in Visual Studio 2026

1 week ago 8
ARTICLE AD BOX

As far as I know the fastest assembly code for testing that a floating point variable contains Not-a-Number (std::isnan) is comparing it to itself, where not-equal will signify NaN. And as I can see, GCC and Clang both produce such assembly code for std::isnan.

But in the latest Visual Studio, std::isnan is not always optimized as can be shown by the following program:

#include <cmath> bool f( double x, double y ) { return std::isnan( x / y ); } double x, y; int main() { return f( x, y ); }

If compiled with most speed optimizations /Ox, for the function f MSVC produces an optimal assembly indeed:

ucomisd xmm0, xmm0 setp al

but the function main is not optimal at all, and instead of ucomisd it contains a call to some internal function _dclass with post processing of its output:

call _dclass xor ecx, ecx cmp ax, 2 sete cl mov eax, ecx

Online demo

What determines in MSVC how std::isnan will be optimized, and how one can ensure that ucomisd will be used for best performance?

Read Entire Article