Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does int i = 10; i / 0; compile, but 5 / 0 gives CS0020 - Division by constant zero? [duplicate]

Tags:

c#

Consider the following snippet:

int i = 5 / 0;

This gives compiler error CS0020: Division by constant zero, which is fine. However, the next snippet:

int i = 10;
i = i / 0;

Compiles just fine.

Does someone know why? I see no reason why the compiler allows an integer variable to be divided by a zero integer constant.

like image 788
Nick Avatar asked Mar 22 '19 12:03

Nick


1 Answers

In the general case, the compiler has no reason to disallow division by zero (or any other number) at runtime.

Your first example, though, is a compile time constant, i.e. it's calculated by the compiler and replaced with the result of the evaluation. This is what the compiler's complaining about as it rightly doesn't know what integer value to put in place of 5/0.

like image 199
Philip C Avatar answered Oct 05 '22 19:10

Philip C