Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why we can not define a variable twice in switch? [duplicate]

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?

like image 823
Alexander Kulyakhtin Avatar asked Feb 25 '14 11:02

Alexander Kulyakhtin


People also ask

Which variable is not allowed in switch statement?

The switch statement doesn't accept arguments of type long, float, double,boolean or any object besides String.

Can we define variable inside switch case?

Declaring a variable inside a switch block is fine. Declaring after a case guard is not.

Can you define a variable twice in Java?

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.

Why are variables not allowed to be used as the case values in a switch?

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 .


1 Answers

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; } 
like image 72
stinepike Avatar answered Sep 28 '22 08:09

stinepike