问题描述
当在无限循环之后写入某些语句时,该语句将成为无法访问的代码。例如:
When there is some statement written after the infinite loop, that statement becomes the unreachable code. For ex:
for(;;)
{
}
Sytem.out.println("Test-1"); //unreachable code
但我在这里面临一些困难。
But I am facing some difficulty here.
请查看以下两个代码段:
Look at the two code snippets below:
代码段1:
for(final int z=4;z<6;)
{
}
System.out.println("Test-2"); //unreachable code
这里,最后一个语句必须是不可达的,因为循环是无限的,输出是正如预期的那样。
Here, The last statement must be unreachable because the loop is infinite and the output is as expected.
Code Snippet2:
Code Snippet2:
final int z=4;
for(;;)
{
if(z<2)
break;
}
System.out.println("Test-3"); //not unreachable
从概念上讲,上面代码中的for循环也是无限的,因为z是final和 if(z 仅在编译时确定.if条件永远不会为真且循环永远不会中断。
但是,上面代码中的Last语句是无法访问的。
Conceptually, the for loop in above code is also infinite since z is final and if(z<2)
is determined at compile time only.The if condition will never be true and the loop will never break.But, the Last statement in above code is not unreachable.
问题:
-
为什么会这样?
Why this is happening ?
任何人都可以告诉我确切的规则,看看代码是否无法访问。
Can anyone tell me the exact rules by which we can see whether code is unreachable or not.
推荐答案
是:
本节专门用于解释
可达这个词。我们的想法是,从构造函数,方法,实例
初始化程序或包含
语句本身语句的静态初始化程序开始,必须有一些可能的执行
路径。该分析考虑了
语句的结构。 除了对while,do和
语句的特殊处理,其条件表达式的常量值为true,表达式的
值在流分析中不予考虑。
因此,编译器不会在您的<$中评估 z< 2
c $ c> if()语句,并且不知道
它永远不会评估为 true
。
Hence the compiler does not evaluate z<2
in your if()
statement, and does not knowthat it will never evaluate to true
.
就Java规范而言,这定义了无法访问的代码。编译器遵守规范很重要,因为更改规则可能会使用于编译的代码无法编译。
This defines unreachable code as far as the Java spec is concerned. It's important that compilers adhere to to the spec, because changing the rules could make code that used to compile fail to compile.
然而,编译器可以自由地给出警告而不是编译错误。
However, compilers are free to give warnings rather than compilation errors.
如果我在Eclipse中输入以下代码:
If I type the following code into Eclipse:
final int x = 0;
if(x == 1) {
System.out.println("This never happens");
}
...我收到警告死码。编译器知道无法访问代码 - 但它无法拒绝编译,因为根据Java规范,代码不能正式无法访问。
... I get the warning "Dead code". The compiler knows the code can't be reached - but it can't refuse to compile, because the code is not formally "unreachable" according to the Java spec.
这篇关于什么时候条件是“无法访问的代码”。发生在Java?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!