gpt4 book ai didi

java - 当 if 条件为常量时,为什么无法检测到无法访问的代码?

转载 作者:行者123 更新时间:2023-12-02 01:08:38 25 4
gpt4 key购买 nike

我正在准备 Java 考试,遇到了“无法访问的语句”编译器错误,例如:

Source.java:10: error: unreachable statement
System.out.println("This code is not reachable");

我试图了解这种情况何时会发生或不会发生 - 例如对于这些情况不会发生:

// Case #1
if (true) {
System.out.println("This code is reachable");
} else {
System.out.println("This code is not reachable"); // Compiles OK
}

// Case #2
for (i = 0; i < 5; i++) {
if (true) continue;
System.out.println("This code is not reachable"); // Compiles OK
}

编译器似乎不够智能,无法检测 if 条件何时始终为 true - 有人可以提供更详细的解释吗?

最佳答案

来自 Java 语言规范,14.21. Unreachable Statements (我强调的):

It is a compile-time error if a statement cannot be executed because it is unreachable.

This section is devoted to a precise explanation of the word "reachable." The idea is that there must be some possible execution path from the beginning of the constructor, method, instance initializer, or static initializer that contains the statement to the statement itself. The analysis takes into account the structure of statements. Except for the special treatment of while, do, and for statements whose condition expression has the constant value true, the values of expressions are not taken into account in the flow analysis.

因此,虽然代码确实无法访问,但编译器明确并不认为它是不可访问的。所说的原因是为了允许程序员定义“标志”变量,例如

static final boolean DEBUG = false;

if (DEBUG) { x=3; }

应该可以在 falsetrue 之间切换 DEBUG,而无需更改代码中的任何其他内容(由于编译错误) .

关于java - 当 if 条件为常量时,为什么无法检测到无法访问的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59705536/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com