变量在开关情况下的作用域

我想我不明白在开关箱里瞄准镜是怎么工作的。

有人能解释一下为什么第一个代码不能编译而第二个能编译吗?

代码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中?

如果我跳过情况1的声明,变量“ str”永远不会被声明..。

49345 次浏览

The scope of the variable is the whole switch statement -- all cases and default, if included.

Here are some other options...

Option 1:

int key = 2;
switch (key) {
case 1:
return "1";
case 2:
return "2";
}

Option 2:

int key = 2;
String str = null;
switch (key) {
case 1:
str = "1";
return str;
case 2:
str = "2";
return str;
}

Several cases can be executed in one switch statement. So..

The scope of a variable exists between the braces of the switch and if statements. In example Code 1 the switch braces enclose both declarations of the variables which will cause the compiler to error as the name to variable binding will have already been made.

In the other example it is ok because both variables are declared within their own braces (scope).

You seem to be assuming that each case is a block with its own local scope, as if/else blocks. It's not.

It's important to correct this conceptual mistake, because otherwise you'll end falling in the frequent trap of forgetting the break inside the case

In the first case the scope of the String declaration is within the switch statement therefore it is shown as duplicate while in the second the string is enclosed within curly braces which limits the scope within the if/else conditions,therefore it is not an error in the second 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;
}
}

The resulting code will now compile successfully since the variable named str in each case clause is in its own scope.

I think it's a valid question, and scope assumption for case statment is unavoidable. Adjusting ourselves to it because java writer has made this not correct.

e.g. if statement by default take first line in its scope than what's wrong with cases where the end of case is explicitly closed by break statement. Hence the declaration in case 1: should not be available in case 2 and it has parallel scope but not nested.