Hi all,
By design, why does the C# compiler allows any float or double values to be divided by zero?
class Program
{
static void Main(string[] args)
{
double x = 0.0 / 0;
float y = 1f / 0;
}
}
Hi all,
By design, why does the C# compiler allows any float or double values to be divided by zero?
class Program
{
static void Main(string[] args)
{
double x = 0.0 / 0;
float y = 1f / 0;
}
}
Because IEEE 754 floating-point values have special non-numeric values to deal with this:
PS Home:\> 1.0/0
Infinity
PS Home:\> 0.0/0
NaN
whereas dividing an integer by zero is always an exception (in the C# sense1), so you could just throw the exception directly.
1 Dividing a floating-point number by zero is also an exception but at a completely different level and many programming languages abstract this away.
Because floating point values have a valid (and genuinely useful) representation of infinity, whereas integers of any type do not.
The reason the compiler allows you to divide a float or a double by zero, is that float and double have representations on the notion of positive infinity and negative infinity (and "not a number"), so it is a meaningful thing to allow.
One oddity is that the compiler fails spot
decimal d = 2;
decimal d2 = d/0M
as a divide by zero, even though it does spot it if you write the equivalent code for an integer.