Why does C# allow dividing a non-zero number by zero in floating-point type?

According to Microsoft, "Floating-point arithmetic overflow or division by zero never throws an exception, because floating-point types are based on IEEE 754 and so have provisions for representing infinity and NaN (Not a Number)."

More on this here.


Mathematically, there is no difference. With computers, however, only the standard IEEE-754 floating-point specification has special values for representing ±∞. Integers can only hold... integers :-)


The IEEE Standard for Floating-Point Arithmetic (IEEE 754) is the most widely-used standard for floating-point computation, and is followed by many hardware and software implementations, including the C# compiler.

This means that a floating-point variable in C# can contain a bit pattern that represents strange creatures such as PositiveInfinity, NegativeInfinity, and Not-a-Number (abbreviated as NaN). Under the IEEE 754 arithmetic rules, any of these non-finite floating-point values can be generated by certain operations. For example, an invalid floating-point operation such as dividing zero by zero results in NaN.

In your specific examples, you can see that C# (unlike VB) overloads the / operator to mean either integer or floating-point division, depending on the numeric types of the numbers involved.

In the first example the compiler sees 1.0, and therefore uses floating-point division and puts the result into a floating-point variable. That variable contains a representation of infinity.

In the second example the compiler sees 1, and therefore uses integer division and puts the result into an integer variable. Because integral types in C# use two's complement system for representation, and don't use any special bit patterns to represent infinity (or NaN), the compiler gives an error.

There are also other interesting floating-point subtleties. And it's worth reading Eric Lippert's blog entry on the subject.