无法访问的代码:错误或警告? [英] Unreachable code: error or warning?

查看:156
本文介绍了无法访问的代码:错误或警告?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个语言设计问题:



您认为无法访问的代码警告(即报告问题并进行编译)或错误(拒绝编译)?



强烈的感觉应该是一个错误:如果程序员写一段代码,它应该总是在实际运行它在一些情况下。但是,C#编译器似乎不同意这一点,只是报告一个警告。



注意:我意识到好的死代码检测是一个非常困难的问题,但这不是这个问题的重点。



下面是一些代码段的例子,其中一些语句明显不可达:

  return; 
foo();

-

  throw new Exception(); 
foo();

-

  if(...){
return;
} else {
throw new Exception();
}
foo();


解决方案

一般来说应该是错误。 >

但我有一个例外:

  if(false){
doStuffThatITemporarilyDisabled();
}

有些开发者可能会抱怨如果你的编译器拒绝编译这样的代码。 p>

This is a language design question:

Do you think unreachable code (in programming languages in general) should raise a warning (i.e. "report problem and compile anyway") or an error ("refuse to compile")?

Personally I strongly feel it should be an error: if the programmer writes a piece of code, it should always be with the intention of actually running it in some scenario. But the C# compiler for example seems to disagree with this and merely reports a warning.

Note: I realize good dead code detection is a very difficult problem, but that is not the focus of this question.

Here are some examples of pieces of code where some statements are clearly unreachable:

return;
foo();

--

throw new Exception();
foo();

--

if (...) {
  return;
} else {
  throw new Exception();
}
foo();

解决方案

Generally speaking it should be an error.

One exception comes to my mind however:

if (false) {
  doStuffThatITemporarilyDisabled();
}

Some developers might complain if your compiler denies compilation for code like that.

这篇关于无法访问的代码:错误或警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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