Why does the compiler not show an error when we try to divide a variable by zero

前端 未结 5 608
野的像风
野的像风 2021-01-06 08:20

If we try to run this code:

int d = 10/0;

We get a compiler error. So we cannot divide by zero.

Now consider this code:

<         


        
相关标签:
5条回答
  • 2021-01-06 08:44

    You'll want to take a look at the C# Language Specification, chapter 7.18. It talks about constant expressions. I'll just summarize the basics.

    The C# compiler makes an effort to try to evaluate an expression at compile time. As long as the operands all have a known value and the operators are simple ones then the compiler can compute the value of the expression at compile time and use the result directly, instead of generating the code to evaluate the expression at runtime. This sounds like an optimization, but it is not quite like that, constant expressions are required in a number of places. Like the value of a case statement, declarations that use the const keyword, the values of an enum declaration and the arguments of an [attribute].

    So no trouble with 10 / 0, that's an expression with literal values and a simple operator so the compiler can directly compute the result and see that it will trigger an exception so complains about it at compile time.

    The d / 0 is not a constant expression because of the d variable. You could argue that the compiler could well know the value of d since it got assigned in the statement above it. But it doesn't do this, optimizing such code is the job of the jitter optimizer.

    0 讨论(0)
  • 2021-01-06 08:50

    the c# compiler is only doing constants value arithmetic check, and there for can tell that you can't do 10/0. it's a lot more then you think for a compiler to do that.

    even more then that: the c# compiler allows:

    1.0 / 0 // Infinity
    

    because:

    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).

    0 讨论(0)
  • 2021-01-06 08:55

    The first:

    int d=10/0;
    

    will be resolved due compile time, because it is constant. The second will not be resolved because the compiler do only syntax checks, not math check.

    0 讨论(0)
  • 2021-01-06 08:56

    Because your d variable is not constant.

    Compiler does only basic (let say trivial) math checks. Your is not basic enough to be done by compiler, because it uses variable that is not const.

    0 讨论(0)
  • 2021-01-06 09:03

    In the first instance, you have two constants, and so the compiler resolves this at compile time, thus finding the error.

    In the second instance, as you have a non const variable(d), the compiler does not resolve this at compile time as it has no way of ensuring the value of d and thus will not spot the error. This will be evaluated at run time, where it will error out.

    0 讨论(0)
提交回复
热议问题