为什么一个的if / else的if / else一个简单的布尔不是给人一种"不可达code"错误 [英] Why is an if/else if/else for a simple boolean not giving an "unreachable code" error
问题描述
这是为什么code没有给人一种不可达code的错误?由于一个布尔值只能是真或假。
公共静态无效的主要(字符串ARGS []){
一个布尔值= FALSE;
如果(A == TRUE){ }否则如果(A == FALSE){ }其他{
INT C = 0;
C = C + 1;
}
}
这是,如果不能执行的语句,因为它是一个不可达编译时错误。
块引用>和
的else语句是可到达的当且仅当的if-then-else语句是可到达。
块引用>您的if-then-else语句是可到达。因此,通过定义编译器认为,其他语句是可到达的。
注:有趣的是下面的code还会编译
//这是确定
如果(假){/ *做某事* /}这是不正确的
,而
//这将无法编译
而(假){/ *做某事* /}因为
可达性的定义,而
是不同的(重点煤矿):
所包含的语句是可到达当且仅当while语句是可到达的和条件前pression不是一个常量前pression,其值为false
块引用>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; } }
解决方案From JLS 14.21. Unreachable Statements
It is a compile-time error if a statement cannot be executed because it is unreachable.
and
The else-statement is reachable iff the if-then-else statement is reachable.
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 */ }
This is not true for
while
// This will not compile while (false) { /* do something */ }
because the reachability definition for
while
is different (emphasis mine):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一个简单的布尔不是给人一种"不可达code"错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!