2

I'm having trouble understanding how the switch statement works. The following code works even the value of a is 4. I understand that each case inside a switch statement is not a block with its own local scope but does that mean that the variable x was declared even a is not equal to 2?

int a = 2;
switch(a){
     case 2:
            int x = 4;
     case 3:
            x = 5;
     case 4: 
            x  = 7;       
}
Tomin B Azhakathu
  • 2,656
  • 1
  • 19
  • 28
glennmark
  • 524
  • 3
  • 13
  • 1
    As noted in the answer to the other question it boils down to this: A declaration isn't really "executable" although initialization is. So even if `int x = 4` is never executed, you've still declared a variable x in the scope of the switch. So x will be declared even if case 2 never runs – Nikos Tzianas Mar 23 '19 at 02:07

1 Answers1

0

Case 1

   int a = 2;
   switch(a){

        case 2:
            int x = 4;
            // executes
        case 3:
             x = 5;
            // executes
        case 4: 
             x  = 7;
            // executes

    }

in this value of x will be 7 because the switch won't break if it find a matching case.

Case 2

If you want to stop execution on 2 do the following

   int a = 2;
   switch(a){

        case 2:
            int x = 4; // variable declaration works even if case wont match. Validity inside switch for every line of code after this line
            break;
            // executes and break
        case 3:
             x = 5;
            break;
            // executes and break
        case 4: 
             x  = 7;
            break;
            // executes and break
       default:
            // write default case here
    }

You need not use int in every x because of the scope of the declaration throughout the scope.

The scope of the declaration of a variable in the switch will affect the following statements or line of code in the switch. It's because, if the variable declaration it will if the scope is not defined by braces.

Case 3

   int a = 3;
   switch(a){

        case 2:
            {
                int x = 4;
                break; // u can skip this break to. Then also it will throw error.
                // x is local variable inside this braces
            }
            // executes
        case 3:
             x = 5;
            // error
        case 4: 
             x  = 7;
            // error
        System.out.println(""+x);    


    }

In the above case, it will through the error. Because its scope is only in that case. In this scenario, the scope of a variable is declared inside the braces. so outside that braces, x won't work. Because x is a local variable in that case condition.

Tomin B Azhakathu
  • 2,656
  • 1
  • 19
  • 28