Int vs Double and division by zero exception

We get a compile-time error when the integer is divided by zero, while in the case of double there is no compilation error, but at runtime we get the infinity / NaN as a result. Any idea why int and double have different behavior when divided by zero exception?

void Main() { int number = 20; var result1 = number/0; // Divide by zero compile time exception double doubleNumber = 20; var result2 = doubleNumber/0.0; // no compile time error. Result is infinity or NaN } 
+4
source share
3 answers

Because it is as defined . If for integers there are no special values ​​for infinity and NaN, therefore, the compiler throws an error if it can detect a problem at compile time.

+6
source

Due to their mathematical background. Infinity is defined for floating point numbers, but not for integers.

+1
source

theoretically, division by zero should lead to infinity, but the integer data type has nothing to represent infinity. double data type, so there is no need to throw an exception there.

+1
source

Source: https://habr.com/ru/post/1402826/


All Articles