java - 在switch case语句中如何声明范围?
以下 java 代码在 Java 1.7 中执行没有错误
The following java code executes without error in Java 1.7
public static void main(String[] args) {
int x = 5;
switch(x) {
case 4:
int y = 3423432;
break;
case 5: {
y = 33;
}
}
}
由于声明永远不会运行,java 如何确定 y 是一个 int.当 case 语句中不使用大括号时,case 语句中的变量声明是否会被限定为 switch 语句级别?
How does java figure out that y is an int since the declaration never gets run. Does the declaration of variables within a case statement get scoped to the switch statement level when braces are not used in a case statement?
推荐答案
声明不是运行"——它们不是需要执行的东西,它们只是告诉编译器变量的类型.(初始化程序会运行,但这很好 - 在为变量赋值之前,您不会尝试从变量中读取.)
Declarations aren't "run" - they're not something that needs to execute, they just tell the compiler the type of a variable. (An initializer would run, but that's fine - you're not trying to read from the variable before assigning a value to it.)
switch 语句中的作用域确实很奇怪,但基本上第一个 case
中声明的变量仍然在第二个 case
的作用域内.
Scoping within switch statements is definitely odd, but basically the variable declared in the first case
is still in scope in the second case
.
来自 JLS 的第 6.3 节:
块中局部变量声明的范围(第 14.4 节)是声明出现的块的其余部分,从它自己的初始化程序开始,包括局部变量声明语句右侧的任何进一步的声明符.
The scope of a local variable declaration in a block (§14.4) is the rest of the block in which the declaration appears, starting with its own initializer and including any further declarators to the right in the local variable declaration statement.
除非您创建额外的块,否则整个 switch 语句就是一个块.如果您想为每种情况创建一个新范围,您可以使用大括号:
Unless you create extra blocks, the whole switch statement is one block. If you want a new scope for each case, you can use braces:
case 1: {
int y = 7;
...
}
case 2: {
int y = 5;
...
}
相关文章