0

As a follow up from my previous question, I noticed odd behaviour (with the console) when dividing by zero. I found that the following two statements compile fine:

Console.WriteLine(1d / 0d);
Console.WriteLine(1f / 0f);

Whereas these two give a compile time error:

Console.WriteLine(1 / 0);
Console.WriteLine(1m / 0m);

Of

Division by constant zero

Why is there this difference in behaviour?

Community
  • 1
  • 1
TheLethalCoder
  • 6,668
  • 6
  • 34
  • 69
  • @JeroenVannevel My question is about compile time errors but I assume the reason is the same as the run time error, thanks – TheLethalCoder Dec 01 '16 at 11:00
  • This questions are correlated but it is not a true duplicate : emphasis on compile time error. The other was "why double allow division by 0" – Guillaume Dec 01 '16 at 11:25
  • @Guillaume Although the duplicate answers the question and covers compile and run time errors/exceptions in I, so I believe it is still a dupe – TheLethalCoder Dec 01 '16 at 11:27
  • The behavior is different between compile time and run time evaluation. This question is also about the compiler being unable to produce IL from an expression that has a defined behavior (DivideByZeroException) when evaluted at run time. – Guillaume Dec 01 '16 at 11:36

1 Answers1

0

Division by 0 is allowed for float and double types. It returns infinity.

For Int32 and Decimal, it is not allowed, it raises an exception. The compiler doesn't allow division by 0 on constant values because it leads to undefined behavior.

public class MyConsts {
public const int i = 1/0; // Constant, compile time evaluation
}

...

Console.WriteLine(MyConsts.i); // What would you expect ?

The compiler is unable to compute a proper value for your constant expression. Keep in mind that the value is compiled and not evaluated at runtime so it's not possible to raise an exception.

Guillaume
  • 12,824
  • 3
  • 40
  • 48