简体   繁体   中英

Why does std::isnan() return false for double variable with NAN value

I decided to use NAN (also tried std::numeric_limits::quiet_NaN() ) as default value for argument of the function, but when i tried to check it using std::isnan , it returned false . In the same time value was printed to console using qDebug() and i saw nan .

Also i tried to check for NAN using x != x rule. It worked for NAN != NAN , but got false for x != x .

Last try was to define NAN double variable inside of the function and try to check it using both methods, but it lead to the same results.

I cant understand what is wrong.

Example:

double abc = NAN;
qDebug()<< abc << (abc != abc) << std::isnan(abc);

Output:

nan false false

I didn't know that we are using -ffast-math in our project. That is what leads to the problem. Thank you for your attention and comments. There is no solution if you are using -ffast-math . You just need to look for another way to solve your problem (without NAN )

std::optional<double> would do it, and then at your leisure you could specialize it to use the explicit NAN bit pattern to indicate an unset value. This value would not be passed via FPU registers, and -ffast-math would not affect it. Not only would you clearly indicate the intent of an optional argument, but you'd make it compiler-proof :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM