问题描述
如果我有这样的代码
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 循环
中的代码无法访问.为什么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?
推荐答案
如 Java 语言规范,这个特性是为条件编译"保留的.
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;
以及使用这个常量的代码
and the code that uses this constant
if (DEBUG) { x=3; }
这个想法是提供一种可能性,可以轻松地将 DEBUG
从 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 循环的情况下才识别无法访问的代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!