What are the backgrounds for a switch-case to not accept this operator?
Because case
requires constant expression as its value. And since an ||
expression is not a compile time constant, it is not allowed.
From JLS Section 14.11:
Switch label should have following syntax:
SwitchLabel:
case ConstantExpression :
case EnumConstantName :
default :
Under the hood:
The reason behind allowing just constant expression with cases can be understood from the JVM Spec Section 3.10 - Compiling Switches:
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.
So, for the cases label to be used by tableswitch
as a index into the table of target offsets, the value of the case should be known at compile time. That is only possible if the case value is a constant expression. And ||
expression will be evaluated at runtime, and the value will only be available at that time.
From the same JVM section, the following switch-case
:
switch (i) {
case 0: return 0;
case 1: return 1;
case 2: return 2;
default: return -1;
}
is compiled to:
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
So, if the case
value is not a constant expressions, compiler won't be able to index it into the table of instruction pointers, using tableswitch
instruction.
||
is essentially the default operation of a case statement in the absence ofbreak
. – Brainwhen Some_Value | Some_Other_Value =>
in acase
statement. But the language doesn't use | as an operator, so there's no way this syntax could be ambiguous. Using || for this purpose in C (Java, etc.) would make the syntax ambiguous, and it's not a good idea to have funky rules with exceptions (like || means one thing in an expression except that it means something different in a different context...). – Plasterboard