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 没有给出“无法访问的代码"?错误
基础教程推荐
- Struts2 URL 无法访问 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
