以下代码自 x=3
起无法编译无法访问
while (false) { x=3; }
但是为什么for( int i = 0; i< 0; i++) {x = 3;}
编译正常吗?在此代码中x=3
也是无法访问的。
最佳答案
参见JLS 14.21, Unreachable Statements .
The contained statement [in a while loop] is reachable iff the while statement is reachable and the condition expression is not a constant expression whose value is false.
false
是一个常量表达式,其值为 false
,所以x=3;
无法访问。
The contained statement [in a basic for loop] is reachable iff the for statement is reachable and the condition expression is not a constant expression whose value is false.
i<0
不是常量表达式,因此所包含的语句被认为是可访问的,即使它实际上不可访问。
关于java - while 和 if 语句中无法访问代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58797600/