First of all I want to note that to find out the rules for working with floating point numbers in c
or c++
you need to check the values of the corresponding constants. Those. standards of languages do not guarantee the existence of these rules, but there is a possibility to find out whether this or that implementation supports, for example, the IEEE-754 standard for a particular type.
Appendix F
( IEC 60559 floating-point arithmetic ) of the c
standard clearly states:
An implementation that defines __STDC_IEC_559__ shall conform to this specification.
In c++
you can check IEEE-754 support for a real type with the following code:
std::numeric_limits<T>::is_iec559
True if and only type adheres to IEC 559 standard.
International Electrotechnical Commission Standard 559 is the same as IEEE 754.
If support is provided, then further investigation of the issue should be carried out according to the mentioned standard. But as practice shows, a division by zero error occurs exclusively when dividing by zero, although infinity can also be obtained when dividing by a nonzero value:
#include <iostream> #include <cfenv> #include <limits> int main() { std::feclearexcept(FE_ALL_EXCEPT); float min = std::numeric_limits<float>::min(); volatile float zero = 0.0f; std::cout << 10.f / min << '\n'; if(std::fetestexcept(FE_DIVBYZERO)) { std::cout << "division by zero reported\n"; } else { std::cout << "division by zero not reported\n"; } }
We get:
inf division by zero not reported
If we replace min
by zero
, then already :
inf division by zero reported
Therefore, you have to decide for yourself what you really want to avoid: the error of dividing by zero or getting infinity.
According to IEEE-754 p. 7.3, the "division by zero" exception occurs only when acting on the final operands in two cases:
- division of a non-zero value by zero;
- calculation of the logarithm of zero.