What are the backgrounds for a switch-case to not accept this operator?
因为情况需要恒定表达式作为其值.而且由于||表达式不是编译时常数,不允许.
开关标签应具有以下语法:
SwitchLabel:
case ConstantExpression :
case EnumConstantName :
default :
在引擎盖下:
Compilation of switch statements uses the tableswitch and lookupswitch instructions. The tableswitch instruction is used when the cases of the switch can be efficiently represented as indices into a table of target offsets. The default target of the switch is used if the value of the expression of the switch falls outside the range of valid indices.
因此,对于由表开关使用的标签作为目标偏移表的索引,在编译时应该知道该值.只有当case值是一个常量表达式时才有可能.和||表达式将在运行时进行评估,该值仅在当时可用.
从相同的JVM部分,以下switch-case:
switch (i) {
case 0: return 0;
case 1: return 1;
case 2: return 2;
default: return -1;
}
编译为:
0 iload_1 // Push local variable 1 (argument i)
1 tableswitch 0 to 2: // Valid indices are 0 through 2 (NOTICE This instruction?)
0: 28 // If i is 0, continue at 28
1: 30 // If i is 1, continue at 30
2: 32 // If i is 2, continue at 32
default:34 // Otherwise, continue at 34
28 iconst_0 // i was 0; push int constant 0...
29 ireturn // ...and return it
30 iconst_1 // i was 1; push int constant 1...
31 ireturn // ...and return it
32 iconst_2 // i was 2; push int constant 2...
33 ireturn // ...and return it
34 iconst_m1 // otherwise push int constant -1...
35 ireturn // ...and return it
因此,如果case值不是常量表达式,编译器将无法使用tableswitch指令将其索引到指令表指针中.