当我们尝试将变量除以零时,为什么编译器没有显示错误 [英] Why does the compiler not show an error when we try to divide a variable by zero

查看:36
本文介绍了当我们尝试将变量除以零时,为什么编译器没有显示错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我们尝试运行此代码:

If we try to run this code:

int d = 10/0;

我们收到一个编译器错误.所以我们不能除以零.

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

现在考虑以下代码:

  int d = 10;
  int o = d / 0;

d可以有任何东西,并且不能将其除以零是不可能的

我们没有收到编译器错误.该变量具有我们不能除以零的任何内容.当我们尝试将变量除以零时,为什么编译器没有给出错误?

We don't get a compiler error. The variable has anything we cannot divide by zero. Why does the compiler not give an error when we try to divide a variable by zero?

推荐答案

您需要看一下C#语言规范的第7.18章.它讨论了常量表达式.我将仅概述基础知识.

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.

C#编译器努力尝试在编译时评估表达式.只要操作数都具有已知值,并且运算符是简单的运算符,则编译器可以在编译时计算表达式的值并直接使用结果,而不是在运行时生成代码来对表达式求值.这听起来像是一种优化,但并非完全如此,常量表达式在许多地方都是 required .像 case 语句的值,使用 const 关键字的声明, enum 声明的值以及[attribute]的参数一样

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

所以 10/0 没问题,那是一个带有文字值和简单运算符的表达式,因此编译器可以直接计算结果并看到它将触发异常,因此在编译时会抱怨它时间.

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.

由于 d 变量, d/0 不是一个常量表达式.您可能会争辩说,由于编译器已经在其上面的语句中分配了 d 的值,因此很容易知道.但这并没有做到,优化这种代码是抖动优化器的工作.

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.

这篇关于当我们尝试将变量除以零时,为什么编译器没有显示错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆