I am learning about the NaN
datatype, so, I ran a code to understand it and it goes well, the code worked as expected, but when I add a line #pragma GCC optimize("Ofast")
in my code then, it behaves unexpected. I am curious why??
#pragma GCC optimize("Ofast")
// C code to check for NaN exception
// using "==" operator
#include <cmath>
#include <iostream>
using namespace std;
// Driver Code
int main()
{
float a = sqrt(2);
float b = sqrt(-2);
// Returns true, a is real number
// prints "Its a real number"
a == a ? cout << "Its a real number" << endl
: cout << "Its NaN" << endl;
// Returns false, b is complex number
// prints "Its nan"
b == b ? cout << "Its a real number" << endl
: cout << "Its NaN" << endl;
return 0;
}
The ouput without pragma is
Its a real number
Its NaN
But after using pragma it gives
Its a real number
Its a real number
CodePudding user response:
-Ofast turns on -ffast-math, which turns on -ffinite-math-only, which does the following (from the gcc documentation here: https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html)
-ffinite-math-only
Allow optimizations for floating-point arithmetic that assume that arguments and results are not NaNs or -Infs.
This option is not turned on by any -O option since it can result in incorrect output for programs that depend on an exact implementation of IEEE or ISO rules/specifications for math functions. It may, however, yield faster code for programs that do not require the guarantees of these specifications.
I think the "-O option" part is wrong since the -Ofast documentation says it "disregards strict standards compliance". That, or by "any -O option" they mean -O1, -O2, -O3.