Why this is illegal:
switch(x) { case 1: int a = 1; break; case 2: int a = 2; break; }
It looks like it could have been legal. What are some deeper reasons for that to be illegal?
The switch statement doesn't accept arguments of type long, float, double,boolean or any object besides String.
Declaring a variable inside a switch block is fine. Declaring after a case guard is not.
You can define a constant twice in a block. You can define a variable twice in a block. The value of a variable can be changed. The result of an integer division is the integer part of the division; the fraction part is truncated.
If the cases were allowed to contain variables, the compiler would have to emit code that first evaluates these expressions and then compares the switch value against more than one other value. If that was the case, a switch statement would be just a syntactically-sugarized version of a chain of if and else if .
if the break statements are not used, Then we know that the following cases will be executed. So if you are permitted to declare in both cases that will cause a conflict. For example
switch(x) { case 1: int a = 1; // i have removed the break; case 2: int a = 2; // now what will happen here :) break; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With