[英]Why is an if/else if/else for a simple boolean not giving an “unreachable code” error
为什么这段代码没有给出“无法访问的代码”错误? 因为布尔值只能是真或假。
public static void main(String args[]) {
boolean a = false;
if (a == true) {
} else if (a == false) {
} else {
int c = 0;
c = c + 1;
}
}
如果由于无法访问语句而无法执行语句,则会出现编译时错误。
和
当 if-then-else 语句可达时,else 语句可达。
您的 if-then-else 语句是可访问的。 因此,根据定义,编译器认为 else 语句是可达的。
注意:有趣的是,下面的代码也可以编译
// This is ok
if (false) { /* do something */ }
这不是真正的while
// This will not compile
while (false) { /* do something */ }
因为while
的可达性定义是不同的(强调我的):
包含的语句是可到达的,当条件是while 语句是可到达的,并且条件表达式不是值为 false 的常量表达式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.