Division by a constant or by a variable zero

Consider the following code:

#include <iostream>

int main()
{
    double zero = 0;
    const double ZERO = 0.;
    std::cout << 0/zero << "\n"; // -nan
    std::cout << 0/0. << "\n";   // nan
    std::cout << 0/ZERO << "\n"; // nan
}

      

Why 0/zero

does it create -nan

, why is it different from 0/0.

and what is the meaning -nan

?

Demo is here for clang. GCC gives -nan

for all of these cases. Trying to compile with MSVC results in runtime errors for constant values ​​and -nan

for a variable .

Which compiler is more correct in this case?

+3


source to share


1 answer


From C ++ Standard 5.6.4:

If the second operand / or% is zero, the behavior is undefined.



Subsection 0

causes horrible undefined behavior! This way the compiler is free to do anything, including creating NaN

, writing code that crashes, and raiding your refrigerator. There is no more correct behavior.

For floating point types, C ++ has std::numeric_limits<T>::is_iec559

to check if an implementation supports the IEEE 754 standard for floating point types T

.

+2


source







All Articles