Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why don't cases in switch statements have their own scope? [duplicate]

Consider this code:

int num = 0;

switch(num) {
   case 1:
      boolean bool = false;
      break;
   case 2:
      String one;
      String two;
      String three;
      //..simulating lots of vars
      break;
   default:
      bool = true;
      System.out.println(bool);
      break;
}

Since we were allowed to reference a variable declared in another case, this means that even though case 1 wasn't chosen, boolean bool was still declared.

Since default is the last option, and java works from left to right (top to bottom), I'm assuming that the variables in case 2 (and any other cases) will also be declared.

This make me think that the more code you have in the cases declared before the case chosen, the longer it'll take to actually access that case compared to if the chosen case was declared first.

Is there a specific reason switch statements work this way? And wouldn't it be best to use if-else rather than switch statements if there are a lot of cases? (talking processing time, nano-seconds)

like image 724
Vince Avatar asked Sep 29 '22 15:09

Vince


2 Answers

{ } represents a scope and you could use it in any way you like.

In a switch statement:

switch (...) {
}

Everything inside the { } belongs in the same scope. If you want to have the cases have their own scope, you need to use { } like this:

switch (...) {
    case 0: {
    }
    break;
    case 1: {
    }
    break;
}

Similarly, you can use { } do declare scopes within scopes like this:

{
      {
          int i;
      }
      {
          int i;
      }
}
like image 195
gmarintes Avatar answered Oct 02 '22 16:10

gmarintes


Switch statements in Java were patterned after switch statements in C++ were patterned after switch statements in C were probably patterned after switch statements in B ... BCPL (which certainly has the same single-block structure) ...

As a long lost Sun bug report says (about something else), 'the reasons are lost in the mists of time'.

like image 29
user207421 Avatar answered Oct 02 '22 15:10

user207421