开关盒中的变量范围 [英] Variable's scope in a switch case
问题描述
我想我不明白范围在切换情况下是如何工作的。
I think I don't understand how the scope works in a switch case.
有人可以向我解释为什么第一个代码不能编译而是第二个代码是吗?
Can someone explain to me why the first code doesn't compile but the second does ?
代码1:
int key = 2;
switch (key) {
case 1:
String str = "1";
return str;
case 2:
String str = "2"; // duplicate declaration of "str" according to Eclipse.
return str;
}
代码2:
int key = 2;
if (key == 1) {
String str = "1";
return str;
} else if (key == 2) {
String str = "2";
return str;
}
为什么变量str的范围不包含在案例1中?
How come the scope of the variable "str" is not contained within Case 1 ?
如果我跳过案例1的声明,变量str永远不会被声明......
If I skip the declaration of case 1 the variable "str" is never declared...
推荐答案
我将重复其他人所说的内容:每个 case
子句中的变量范围对应于整个切换
语句。但是,您可以使用大括号创建更多嵌套范围,如下所示:
I'll repeat what others have said: the scope of the variables in each case
clause corresponds to the whole switch
statement. You can, however, create further nested scopes with braces as follows:
int key = 2;
switch (key) {
case 1: {
String str = "1";
return str;
}
case 2: {
String str = "2";
return str;
}
}
生成的代码现在将成功编译,因为名为变量每个 case
子句中的 str
都在其自己的范围内。
The resulting code will now compile successfully since the variable named str
in each case
clause is in its own scope.
这篇关于开关盒中的变量范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!