无法访问的代码 while 循环 [英] Unreachable code while loop
本文介绍了无法访问的代码 while 循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我编译这段代码时
public static void main(String [] args) {
int x = 0;
while(false)
{
System.out.println(hello);
}
}
它显示编译时错误无法访问的代码.
it is showing compile time error unreachable code.
但是当我将此代码修改为
But when I modified this code to
public static void main(String [] args) {
int x = 0;
boolean result = false;
while(result)
{
x=4;
}
}
一切正常.
谁能告诉我这种行为背后的原因.
Can somebody tell me the reason behind this behavior.
推荐答案
这是因为 boolean result = false
不是常量表达式,而 false
是.如果您尝试下面的代码,它也不会编译,因为 result
现在是一个常量:
It is because boolean result = false
is not a constant expression whereas false
is. If you try the code below, it won't compile either because result
is now a constant:
final boolean result = false;
while(result) { x=4; }
然而这会编译,因为结果不再是一个常量变量:
However this would compile, because result is not a constant variable any longer:
final boolean result;
result = false;
while(result) { x=4; }
另见:为什么Java 编译器不理解这个变量总是被初始化? 类似的讨论.
这篇关于无法访问的代码 while 循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文