问题描述
如果我有像
public static void main(String args[]){
int x = 0;
while (false) { x=3; } //will not compile
}
编译器会投诉 x = 3
是无法访问的代码,但如果我有代码
compiler will complaint that x=3
is unreachable code but if I have code like
public static void main(String args[]){
int x = 0;
if (false) { x=3; }
for( int i = 0; i< 0; i++) x = 3;
}
然后通过 if语句中的代码正确编译
和 for loop
无法访问。为什么java工作流逻辑没有检测到这种冗余?任何用例?
then it compiles correctly though the code inside if statement
and for loop
is unreachable. Why is this redundancy not detected by java workflow logic ? Any usecase?
推荐答案
如,此功能保留用于条件编译。
As described in Java Language Specification, this feature is reserved for "conditional compilation".
JLS中描述的一个例子是你可能有一个常量
An example, described in the JLS, is that you may have a constant
static final boolean DEBUG = false;
以及使用此常量的代码
if (DEBUG) { x=3; }
想法是提供更改 DEBUG $ c的可能性$ c>从
true
到 false
轻松不对代码进行任何其他更改,如果上面的代码给出了编译错误。
The idea is to provide a possibility to change DEBUG
from true
to false
easily without making any other changes to the code, which would not be possible if the above code gave a compilation error.
这篇关于为什么Java仅在while循环的情况下识别无法访问的代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!