C++ warning: division of double by zero

  • A+

Case 1:

#include <iostream>  int main() {     double d = 15.50;     std::cout<<(d/0.0)<<std::endl; } 

It compiles without any warnings and prints inf. OK, C++ can handle division by zero, (see it live).


Case 2:

#include <iostream>  int main() {     double d = 15.50;     std::cout<<(d/0)<<std::endl; } 

The compiler gives the following warning (see it live):

warning: division by zero [-Wdiv-by-zero]      std::cout<<(d/0)<<std::endl; 

Why does the compiler give a warning in the second case?

Is 0 != 0.0?


#include <iostream>  int main() {     if(0 == 0.0)         std::cout<<"Same"<<std::endl;     else         std::cout<<"Not same"<<std::endl; } 




Floating point division by zero is well defined by IEEE and gives infinity (either positive or negative according to the value of the numerator (or NaN for ±0) ).

For integers, there is no way to represent infinity and the language defines the operation to have undefined behaviour so the compiler helpfully tries to steer you clear from that path.

However in this case, since the numerator is a double, the divisor (0) should be promoted to a double too and there's no reason to give a warning here whilst not giving a warning for 0.0 so I think this is a compiler bug.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: