Why do cases in switch statements not have their own capabilities?

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 refer to a variable declared in another case, this means that even if case 1 not selected, boolean bool was still declared.

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

This makes me think that the more code you have in cases declared before the selected case, the longer it will actually get access to this case compared to the fact that the first case was declared first.

Are there any specific reasons switch statements work with? And would it not be better to use if-else instead of switching with operators if there are many cases? (call processing time, nanoseconds)

+5
source share
2 answers

Switch statements in Java were structured after switch statements in C ++ were structured after switch statements in C were probably patterned after switch statements in B ... BCPL (which, of course, has one and same structure with one block) ...

As stated in Sun's long bug report, (about something else), "the reasons are lost in the fog of time."

+2
source

{} represents the scope, and you can use it in any way.

In the switch statement:

 switch (...) { } 

Everything inside {} belongs to the same area. If you want these cases to have their own scope, you need to use {} as follows:

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

Similarly, you can use {} do to declare scope within scope:

 { { int i; } { int i; } } 
+2
source

Source: https://habr.com/ru/post/1204614/


All Articles