Why is an if/else if/else for a simple boolean not giving an quot;unreachable codequot; error(为什么简单布尔值的 if/else if/else 没有给出“无法访问的代码?错误)
问题描述
为什么这段代码没有给出无法访问的代码"错误?因为布尔值只能是真或假.
Why is this code not giving an "unreachable code" error? Since a boolean can only be true or false.
public static void main(String args[]) {
boolean a = false;
if (a == true) {
} else if (a == false) {
} else {
int c = 0;
c = c + 1;
}
}
推荐答案
来自 JLS 14.21.无法访问的语句
如果由于无法访问而无法执行语句,则为编译时错误.
It is a compile-time error if a statement cannot be executed because it is unreachable.
和
如果 if-then-else 语句可达,则 else 语句可达.
The else-statement is reachable iff the if-then-else statement is reachable.
您的 if-then-else 语句是可访问的.因此,根据定义,编译器认为 else 语句是可访问的.
Your if-then-else statement is reachable. So, by the definition the compiler thinks that the else-statement is reachable.
注意:有趣的是,下面的代码也可以编译
Note: Interestingly the following code also compiles
// This is ok
if (false) { /* do something */ }
这不适用于 while
// This will not compile
while (false) { /* do something */ }
因为 while
的可达性定义不同(强调我的):
because the reachability definition for while
is different (emphasis mine):
如果while语句可达且条件表达式不是值为false的常量表达式,则包含的语句是可达的.
The contained statement is reachable iff the while statement is reachable and the condition expression is not a constant expression whose value is false.
这篇关于为什么简单布尔值的 if/else if/else 没有给出“无法访问的代码"?错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么简单布尔值的 if/else if/else 没有给出“无法访问的代码"?错误


基础教程推荐
- 从 python 访问 JVM 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01