Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ warning: division of double by zero

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).

But,

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?

Edit:

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

output:

Same 
like image 618
Jayesh Avatar asked Jul 23 '18 08:07

Jayesh


People also ask

What happens if you divide by zero in C?

Because what happens is that if we can say that zero, 5, or basically any number, then that means that that "c" is not unique. So, in this scenario the first part doesn't work. So, that means that this is going to be undefined. So zero divided by zero is undefined.

What type of error is dividing by zero in C?

Dividing a number by Zero is a mathematical error (not defined) and we can use exception handling to gracefully overcome such operations. If you write a code without using exception handling then the output of division by zero will be shown as infinity which cannot be further processed.

Why is double divided by infinity zero?

In case of double/float division, the output is Infinity, the basic reason behind that it implements the floating point arithmetic algorithm which specifies a special values like “Not a number” OR “infinity” for “divided by zero cases” as per IEEE 754 standards.

Can you divide a float by 0?

Values like INFINITY and NaN are available for floating-point numbers but not for integers. As a result, dividing an integer by zero will result in an exception. However, for a float or double, Java allows the operation.


1 Answers

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.

like image 197
Motti Avatar answered Oct 14 '22 10:10

Motti